简体   繁体   English

使用Iterable无法从Java中的自定义链接列表中检索数据

[英]Not able to retrieve data from custom linked list in java using Iterable

I have a custom linked list class in java implementing Iterable interface.. I am able to add data to the head of the linked list.The main problem is that I can add data into the list but I am not able to iterate over the entire list. 我在实现Iterable接口的java中有一个自定义的链表类。我能够将数据添加到链表的头部。主要问题是我可以将数据添加到链表中,但无法遍历整个列表名单。

 public class LL<T> implements Iterable<T> { private Node<T> head; /** * Default constructor * * @param head */ public LL() { super(); this.head = new Node<T>(null); } /** * Inserts a new node at the beginning of this list. */ public void addNode(T data) { Node<T> newNode = new Node<T>(data, head.next); head = newNode; // System.out.println("Added " + head.data); } /** * * @param head * @return */ public T getNode() { return head.data; } public T getIthNode(int index) { if (index <= 0) return null; Node<T> current = head; int i = 1; while (current.next != null && i <= index) { i++; current = current.next; } return current.data; } @Override public Iterator<T> iterator() { return new ListIterator<T>(); } public class ListIterator<T> implements Iterator<T> { private Node<T> currentNode; /** * @param currentNode */ public ListIterator() { super(); this.currentNode = (Node<T>) head; } @Override public boolean hasNext() { if (currentNode.next != null && currentNode != null) return true; else return false; } @Override public T next() { if (!hasNext()) throw new NoSuchElementException(); T node = currentNode.data; currentNode = currentNode.next; return node; } @Override public void remove() { // TODO Auto-generated method stub } } // Same as using struct in C private static class Node<T> { private T data; private Node<T> next; /** * @param data * @param next */ public Node(T data, Node<T> next) { super(); this.data = data; this.next = next; } /** * @param next */ public Node(Node<T> next) { super(); this.data = null; this.next = next; } } public static void main(String[] args) { LL<String> list = new LL<String>(); list.addNode("aaaa"); list.addNode("bbbb"); list.addNode("cccc"); list.addNode("dddd"); // System.out.print(list.getNode()); System.out.print(list.getIthNode(1)); Iterator<String> itr = list.iterator(); while (itr.hasNext()) { System.out.println("iterating"); System.out.println(itr.next()); } } 

Your addNode always makes the new node the head of the list and keeps no reference to the previous head, so it will always have just one node. 您的addNode始终使新节点成为列表的头,并且不引用前一个头,因此它将始终只有一个节点。

Change it to: 更改为:

public void addNode(T data) {
    Node<T> newNode = new Node<T>(data, head);
    head = newNode;
    // System.out.println("Added " + head.data);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM