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

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

我在 java 中有一个自定义链表 class 实现 Iterable 接口。我能够将数据添加到链接的头部 list.The 主要问题是我可以将数据添加到列表中,但我无法遍历整个列表。

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());
  }

 }

您的 addNode 总是使新节点成为列表的头部,并且不保留对前一个头部的引用,因此它始终只有一个节点。

改为:

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