linked list iterator methods code example
Example 1: implementing iterator for linked list java
public class BasicLinkedList<T> implements Iterable<T> {
public int size;
private class Node {
private T data;
private Node next;
private Node(T data) {
this.data = data;
next = null;
}
}
private Node head;
private Node tail;
public BasicLinkedList() {
head = tail = null;
}
public Iterator<T> iterator() {
return new Iterator<T>() {
Node current = head;
@Override
public boolean hasNext() {
return current != null;
}
@Override
public T next() {
if(hasNext()){
T data = current.data;
current = current.next;
return data;
}
return null;
}
@Override
public void remove(){
throw new UnsupportedOperationException("Remove not implemented.");
}
};
Example 2: java linked list iterator
import java.io.*;
import java.util.LinkedList;
import java.util.ListIterator;
public class LinkedListDemo {
public static void main(String args[])
{
LinkedList<String> list = new LinkedList<String>();
list.add("Geeks");
list.add("for");
list.add("Geeks");
list.add("10");
list.add("20");
System.out.println("LinkedList:" + list);
ListIterator list_Iter = list.listIterator(2);
System.out.println("The list is as follows:");
while(list_Iter.hasNext()){
System.out.println(list_Iter.next());
}
}
}