Write a program using LinkedList class and ListIterator interface to demonstrate the following activities:

Question

Write a program using LinkedList class and ListIterator interface to demonstrate the following activities:

1. Create a singly linked list named “Alphabets” with four elements: “P”, “Q”, “R”, and “T” in the same sequence. Create an iterator named “iter1” and attach it to the linked list.
2. Add a new element “O” at the beginning of the linked list.
3. Add a new element “U” at the end of the linked list.
4. Add a new element “S” after the element “R”.
5. Remove the element “O” and “Q”.
6. Display the linked list after performing each activity 1 to 5.

Sample output:
[P, Q, R, T]
[O, P, Q, R, T]
[O, P, Q, R, T, U]
[O, P, Q, R, S, T, U]
[P, R, S, T, U]

Answer (Expert Verified)

The program is an illustration of LinkedList.

What is a LinkedList?

LinkedList is a data structure element that contains nodes where each node represents a value and also points to the next node.

The main program

The program written in Java, where comments are used to explain each line of the program is as follows:

import java.util.LinkedList;

import java.util.Iterator;

class Main {

 public static void main(String[] args) {

     //This creates the Alphabets LinkedList

   LinkedList<String> Alphabets = new LinkedList<String>();

   //This creates an iterator for the Alphabets LinkedList

   Iterator it = Alphabets.iterator();

   //This adds P, Q, R and T to the list

   Alphabets.add(“P”);    Alphabets.add(“Q”);    Alphabets.add(“R”);    Alphabets.add(“T”);

   //This prints the Alphabets LinkedList

   System.out.println(Alphabets);

   //This adds O to the beginning of the list

   Alphabets.addFirst(“O”);

   //This prints the Alphabets LinkedList

   System.out.println(Alphabets);

   //This adds U to the list

   Alphabets.add(“U”);

   //This prints the Alphabets LinkedList

   System.out.println(Alphabets);

   //This adds S after R

   Alphabets.add(4,”S”);

   //This prints the Alphabets LinkedList

   System.out.println(Alphabets);

   //This removes O and Q from the list

   Alphabets.remove(“O”); Alphabets.add(“Q”);

   //This prints the Alphabets LinkedList

   System.out.println(Alphabets);

 }

}

Leave a Comment