Odin
Odin

Reputation: 580

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.

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

	}

Upvotes: 2

Views: 71

Answers (1)

Eran
Eran

Reputation: 393831

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.

Change it to:

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

Upvotes: 3

Related Questions