Hello, I am a beginner to java and needed some assistance...I am writing code to create my own singly linked list, and an iterator that iterates over the elements of the list...however I don't know how to use the iterator to display the elements of the list and I am not sure if my implementation is correct to begin with...everytime i call the iterator it keeps printing "Jack" so I don't know if one of my methods is wrong or my iterator is wrong...please help me out!! thank you so much!!
Heres the code for my singly linked list
import java.util.NoSuchElementException;
public class LinkedList<E>
{
private static class Node<E>
{
public E data;
public Node<E> next;
public Node(E data, Node<E> next)
{
this.data = data;
this.next = next;
}
}
private Node<E> head;
private Node<E> current;
private Node<E> previous;
private int count;
public LinkedList()
{
head = null;
count = 0;
}
public void addToFront(E e)
{
Node<E> newNode = new Node<E> (e, head);
head = newNode;
count++;
}
public void remove(E e)
{
current = head.next;
previous = head;
if (head.equals(e))
{
head = head.next;
count--;
return;
}
else if (!head.equals(e))
{
while (!(current.next == null))
{
if (current.equals(e))
{
previous.next = current.next;
count--;
return;
}
previous = previous.next;
current = current.next;
}
}
else
{
throw new NoSuchElementException();
}
}
public int size()
{
return count;
}
public void clear()
{
head = null;
count = 0;
}
public Iterator iterator()
{
return new Iterator();
}
public class Iterator
{
private Node<E> currentSpot;
public Iterator()
{
currentSpot = head;
}
public boolean hasNext()
{
if (currentSpot != null)
{
return true;
}
else
return false;
}
public E next()
{
if (currentSpot != null)
{
E data = currentSpot.data;
currentSpot = currentSpot.next;
return data;
}
throw new NoSuchElementException();
}
}
}
And here is the main im trying to test my code in
public class LinkedListTest
{
public static void main(String[] args)
{
LinkedList<String> theList = new LinkedList<String>();
theList.addToFront("Ted");
theList.addToFront("Fred");
theList.addToFront("Sid");
theList.addToFront("Jack");
System.out.println(theList.iterator().next());
System.out.println(theList.iterator().next());
}
}