singly linked list iterator java 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;
    }
//Add, remove method 

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

// Java code to illustrate listIterator() 
import java.io.*; 
import java.util.LinkedList; 
import java.util.ListIterator; 
  
public class LinkedListDemo { 
    public static void main(String args[]) 
    { 
        // Creating an empty LinkedList 
        LinkedList<String> list = new LinkedList<String>(); 
  
        // Use add() method to add elements in the list 
        list.add("Geeks"); 
        list.add("for"); 
        list.add("Geeks"); 
        list.add("10"); 
        list.add("20"); 
  
        // Displaying the linkedlist 
        System.out.println("LinkedList:" + list); 
          
        // Setting the ListIterator at a specified position 
        ListIterator list_Iter = list.listIterator(2); 
  
        // Iterating through the created list from the position 
        System.out.println("The list is as follows:"); 
        while(list_Iter.hasNext()){ 
           System.out.println(list_Iter.next()); 
        } 
    } 
}