LinkedList in Java
Introduction [1]
Each element in the LinkedList is called the Node. Each Node of the LinkedList
contains two items:
1) Content of the element
2) Pointer/Address/Reference to the Next Node in the LinkedList.
Note:
1. Head of the LinkedList only contains the Address of the First element of the
List.
2. The Last element of the LinkedList contains null in the pointer part of the node
because it is the end of the List so it doesn’t point to anything as shown in the
above diagram.
Hierarchy of LinkedList class in Java
Used: java.util.*
Method Summary [2]
Example:
import java.util.*;
public class LinkedListExample {
public static void main(String args[]) {
/* Linked List Declaration */
LinkedList<String> linkedlist = new LinkedList<String>();
/*add(String Element) is used for adding
* the elements to the linked list*/
linkedlist.add("Item1");
linkedlist.add("Item5");
linkedlist.add("Item3");
linkedlist.add("Item6");
linkedlist.add("Item2");
/*Display Linked List Content*/
System.out.println("Linked List Content: " +linkedlist);
/*Add First and Last Element*/
linkedlist.addFirst("First Item");
linkedlist.addLast("Last Item");
System.out.println("LinkedList Content after addition: "
+linkedlist);
/*This is how to get and set Values*/
Object firstvar = linkedlist.get(0);
System.out.println("First element: " +firstvar);
linkedlist.set(0, "Changed first item");
Object firstvar2 = linkedlist.get(0);
System.out.println("First element after update by set
method: " +firstvar2);
/*Remove first and last element*/
linkedlist.removeFirst();
linkedlist.removeLast();
System.out.println("LinkedList after deletion of first and
last element: " +linkedlist);
/* Add to a Position and remove from a position*/
linkedlist.add(0, "Newly added item");
linkedlist.remove(2);
System.out.println("Final Content: " +linkedlist);
}
}
Search elements in LinkedList example
import java.util.LinkedList;
public class SearchInLinkedList {
public static void main(String[] args) {
// Step1: Create a LinkedList
LinkedList<String> linkedlist = new LinkedList<String>();
// Step2: Add elements to LinkedList
linkedlist.add("Tim");
linkedlist.add("Rock");
linkedlist.add("Hulk");
linkedlist.add("Rock");
linkedlist.add("James");
linkedlist.add("Rock");
//Searching first occurrence of element
int firstIndex = linkedlist.indexOf("Rock");
System.out.println("First Occurrence: " + firstIndex);
//Searching last occurrence of element
int lastIndex = linkedlist.lastIndexOf("Rock");
System.out.println("Last Occurrence: " + lastIndex);
}
}
Reference
[1] https://beginnersbook.com/
[2] https://docs.oracle.com/javase/7/docs/api/java/util/LinkedList.html