How to Iterate Linklist using Java

LinkedList is java class which implements List interface. Hence same way can be used to iterate LinkList using Iterator.

Java Utils package provides Iterator interface to iterate over collection. LinkedList is part of Collection. You can check whether next elements is available or not using hasNext() method.

If next element is available, next() method is used to retrieve element.

Java Program to iterate LinkedList :
LinkedList list = new LinkedList();
list.add(5);
list.add(1);
list.add(2);
list.add(10);
list.add(6);

// iterate over list
Iterator iterator = list.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}

Output:
5
1
2
10
6

No comments:

Post a Comment