In: Computer Science
Exercise 1:
Write a program in Java to manipulate a Singly Linked List:
1. Create Singly Linked List
2. Display the list
3. Count the number of nodes
4. Insert a new node at the beginning of a Singly Linked
List.
5. Insert a new node at the end of a Singly Linked List
6. Insert a new node after the value 5 of Singly Linked List
7. Delete the node with value 6.
8. Search an existing element in a Singly linked list (the element
of search is given by the user)
9. Call all methods above in main method with the following
data:
Test Data :
Input the number of nodes : 3
Input data for node 1 : 2
Input data for node 2 : 5
Input data for node 3 : 8
import java.util.*;
class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Creating object of the
// class linked list
LinkedList<Integer> ll = new LinkedList<Integer>();
// Adding elements to the linked list
System.out.print("Input the number of nodes:");
int n = input.nextInt();
for(int i=1;i<=n;++i) {
System.out.print("Input data for node " + i + ":");
int temp = input.nextInt();
ll.add(temp);
}
System.out.println(ll);
System.out.println("Number of nodes :" + ll.size());
System.out.print("Node to insert at the begining of the linked list: ");
int front = input.nextInt();
ll.addFirst(front);
System.out.print("Node to insert at the end of the linked list: ");
int back = input.nextInt();
ll.addFirst(back);
System.out.print("Node to insert after 5 of the linked list: ");
int after = input.nextInt();
ll.add(ll.indexOf(5),after);
System.out.print("Enter the node to delete in the linked list: ");
int del = input.nextInt();
ll.removeFirstOccurrence(del);
System.out.print("Enter the node to be searched in linked list: ");
int ser = input.nextInt();
System.out.println(ll.contains(ser));
System.out.print(ll);
}
}
OUTPUT: