Saturday, 4 November 2023

Construct a Linked List containing name: CPP, Java, Python and PHP. Then extend your java program to do the following: Display the contents of the List using an Iterator Display the contents of the List in reverse order using a ListIterator. -core java slip20

 

Construct a Linked List containing name: CPP, Java, Python and PHP. Then extend your java program to do the following:

Display the contents of the List using an Iterator

Display the contents of the List in reverse order using a ListIterator.

 

import java.util.LinkedList;

import java.util.List;

import java.util.ListIterator;

import java.util.Iterator;

 

public class LinkedListDemo {

    public static void main(String[] args) {

        // Create a linked list of names

        List<String> names = new LinkedList<>();

        names.add("CPP");

        names.add("Java");

        names.add("Python");

        names.add("PHP");

 

        // Display the contents of the list using an Iterator

        System.out.println("Contents of the List using an Iterator:");

        Iterator<String> iterator = names.iterator();

        while (iterator.hasNext()) {

            System.out.println(iterator.next());

        }

 

        // Display the contents of the list in reverse order using a ListIterator

        System.out.println("\nContents of the List in Reverse Order using a ListIterator:");

        ListIterator<String> listIterator = names.listIterator(names.size());

        while (listIterator.hasPrevious()) {

            System.out.println(listIterator.previous());

        }

    }

}