In Java, a LinkedList
is part of the java.util
package and represents a collection of elements in a linear sequence. Unlike arrays, a LinkedList
does not store elements in contiguous memory locations, but rather uses nodes to store data and references (links) to other nodes. This gives a LinkedList
its flexibility in terms of dynamic resizing and efficient insertions and deletions.
Each element in a LinkedList
is called a node. A node consists of two parts:
- Data: the actual value stored in the node.
- Next: a reference (or pointer) to the next node in the list.
For a doubly linked list, each node also contains a reference to the previous node.
Basic Operations in a LinkedList
- Add elements: You can add elements at the beginning, end, or at any specific position in the list.
- Remove elements: You can remove the first, last, or any specific element.
- Access elements: Traverse through the list to access any specific element.
- Search: Find an element in the list.
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
import java.util.LinkedList; public class LinkedListExample { public static void main(String[] args) { // Creating a LinkedList LinkedList<String> list = new LinkedList<>(); // Adding elements list.add("Apple"); list.add("Banana"); list.add("Cherry"); // Displaying the list System.out.println("LinkedList: " + list); // Removing an element list.remove("Banana"); System.out.println("After Removal: " + list); // Accessing an element System.out.println("First Element: " + list.getFirst()); } } |
Use Cases
- Implementing stacks and queues
- Navigating through elements in browsers (Back/Forward)
- Dynamic memory allocation (e.g., OS memory management)
- Creating adjacency lists in graphs