In the Java programming language, all linked lists are actually doubly linked.

Iterator

import java.util.*;

public class LinkedListTest
{
   public static void main(String[] args)
   {
      var staff = new LinkedList<String>(); 
      staff.add("Amy"); 
      staff.add("Bob"); 
      staff.add("Carl"); 
      Iterator<String> iter = staff.iterator(); 
      String temp = iter.next();   Return the first element
      System.out.println(temp);    // Amy
      temp = iter.next(); 
      System.out.println(temp);    // Bob
      iter.remove(); 
      
      System.out.println(staff);   // [Amy, Carl]}}Copy the code

ListIterator

The listIterator method is used when inserting or deleting elements in a Linked list.

  • The add method adds the new element before the iterator position.
  • If the linked list has n elements, there are n + 1 spots for adding a new element.
import java.util.*;
/**
 * This program demonstrates operations on linked lists.
 * @versionThe 2018-04-10 * 1.12@author Cay Horstmann
 */
public class LinkedListTest
{
   public static void main(String[] args)
   {
      var a = new LinkedList<String>();
      a.add("Amy");
      a.add("Carl");
      a.add("Erica");

      var b = new LinkedList<String>();
      b.add("Bob");
      b.add("Doug");
      b.add("Frances");
      b.add("Gloria");

      // merge the words from b into a
      ListIterator<String> aIter = a.listIterator();
      Iterator<String> bIter = b.iterator();

      while (bIter.hasNext())
      {
         if (aIter.hasNext()) aIter.next();   
         aIter.add(bIter.next());
      }

      System.out.println(a);

      // remove every second word from b
      bIter = b.iterator();
      while (bIter.hasNext())
      {
         String temp = bIter.next(); // skip one element
         System.out.println(temp); 
         if (bIter.hasNext())
         {
            bIter.next(); // skip next element
            bIter.remove(); // remove that element
         }
      }

      System.out.println(b);      // [Bob, Frances]

      // bulk operation: remove all words in b from a
      a.removeAll(b);
      System.out.println(a);     // [Amy, Carl, Doug, Erica, Gloria]}}Copy the code