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

时间:2015-01-23 10:06:20

标签: java data-structures

我在java中实现了Iterable接口的自定义链表类。我能够将数据添加到链表的头部。主要问题是我可以将数据添加到列表中但是我无法迭代在整个清单上。

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

	}

1 个答案:

答案 0 :(得分:3)

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

将其更改为:

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