In: Computer Science
Create a Linked List and conduct the following operations. Portion of the program is given.
The operations are:
Partial program is:
import java.util.*;
public class LinkedListDemo{
public static void main(String[] args){
LinkedList link=new LinkedList();
link.add(" "); //add something here
link.add(" "); //add something here
link.add(new Integer( )); //add something here
System.out.println("The contents of array is" + link);
System.out.println("The size of an linkedlist is" + link.size());
//add your code
//end your code
}
}
MAKE SURE TO ATTACH THE SCREENSHOT OF THE RUNNING RESULT
I have added inline comments for better understanding. Screenshot of code and output is attached as well.
LinkedListDemo.java:
import java.util.*;
public class LinkedListDemo{
    public static void main(String[] args){
        LinkedList linkedList = new LinkedList();
        //Add an “H” to the list
        linkedList.add("H"); //add something here
        //Add an “I” to the list
        linkedList.add("I"); //add something here
        //Add an 100 to the list
        linkedList.add(100);
        //Print the content of the list and its size
        System.out.println("The size of an linkedlist is: " + linkedList.size());
        System.out.print("The contents of linked list are: ");
        //since we are not using generics here, linkedList will return elements of class Object
        for(Object obj : linkedList){
            System.out.print(obj+" ");
        }
        System.out.println();
        //Add a “H” to the first place of the list
        linkedList.add(0, "H"); // linkedList = {"H","H","I",100}
        //Add a “R” to the last place of the list. add() appends the element in the end of list
        linkedList.add("R"); //linkedList = {"H","H","I",100,"R"}
        //Get the element of position 3 (index = 2) and print it
        System.out.println("Element at position 3 is: "+linkedList.get(2));
        //Get the last element and print it. for last element, index = linkedList.size()-1
        System.out.println("Last element in the list is: "+linkedList.get(linkedList.size()-1));
        //Add an “U” to the list
        linkedList.add("U"); //linkedList = {"H","H","I",100,"R","U"}
        //Add a “?” to the list
        linkedList.add("?"); //linkedList = {"H","H","I",100,"R","U","?"}
        //Remove the element of position 5 (index = 4)
        linkedList.remove(4); //linkedList = {"H","H","I",100,"U","?"} "R" removed
        //Get and print the element of position 5 (index = 4)
        System.out.println("Element at position 5 is: "+linkedList.get(4));
        //Remove the element of first place and print the element
        Object obj = linkedList.remove(0); //linkedList = {"H","I",100,"U","?"} "H" removed at index 0
        System.out.println("Removed element is: "+obj);
    }
}
Output:
