Java Program to demonstrate the use of LinkedList.
Objective
Write a Java program to demonstrate LinkedList operations.
Algorithm / Approach
- Import
java.util.*. - Instantiate a
LinkedList<Integer>. - Use
ll.add(x)to append items. - Use
ll.indexOf(x)to search for an item. - Use
ll.remove(index)to delete an item.
Test.java
import java.util.*;
class Test {
LinkedList<Integer> ll;
Scanner s;
Test() {
ll = new LinkedList<Integer>();
s = new Scanner(System.in);
}
void addElement() {
char c = 'y';
while(c=='y') {
System.out.print("Enter Element: ");
int x = s.nextInt();
ll.add(x);
System.out.print("Want to Add[y/n]: ");
try {
c=(char)System.in.read();
}
catch(Exception e) { }
}
}
void show() {
System.out.println(ll);
System.out.println("Size: "+ll.size());
}
void find() {
System.out.print("Element to find: ");
int x = s.nextInt();
int i = ll.indexOf(x);
if(i == -1) {
System.out.println("NOT in List");
}
else {
System.out.println("Find at "+(i+1));
}
}
void delete() {
System.out.print("Element to delete: ");
int x = s.nextInt();
int index = ll.indexOf(x);
if(index == -1) {
System.out.println("NOT in List");
}
else {
ll.remove(index);
System.out.println("Now List: "+ll);
}
}
public static void main(String[] a)
throws Exception
{
Test t = new Test();
System.out.println("Add in List ");
t.addElement();
t.show();
t.find();
}
}
Expected Output
Add in List Enter Element: 1 Want to Add[y/n]: y Enter Element: 2 Want to Add[y/n]: y Enter Element: 3 Want to Add[y/n]: y Enter Element: 4 Want to Add[y/n]: y Enter Element: 5 Want to Add[y/n]: y Enter Element: 6 Want to Add[y/n]: y Enter Element: 7 Want to Add[y/n]: y Enter Element: 8 Want to Add[y/n]: y Enter Element: 9 Want to Add[y/n]: n [1, 2, 3, 4, 5, 6, 7, 8, 9] Size: 9 Element to find: 12 NOT in List Element to delete: 5 Now List: [1, 2, 3, 4, 6, 7, 8, 9]
Explanation of the Program
LinkedListimplements both theListandDequeinterfaces.- Internally, it uses a doubly-linked list data structure. Each element (node) stores the data as well as memory pointers to both the previous and next nodes in the chain.
- While
ArrayListis faster for retrieving data (using an index),LinkedListis much faster for inserting or deleting data in the middle of the list, because it only requires updating a few pointers rather than shifting thousands of elements in an array.
Complexity
Time Complexity
O(n) - For traversing nodes during search/remove operations.
Space Complexity
O(n)