The LinkedList is a core data structure used to store a sequence of elements. Unlike arrays, which use contiguous memory locations, a LinkedList is made up of nodes, where each node contains data and a reference (or link) to the next node (and optionally the previous one).
🔹 What is a LinkedList?
In Java, LinkedList
is part of the java.util package and implements the List
and Deque
interfaces. It supports dynamic memory allocation, meaning it can grow or shrink in size as needed during runtime.
Each element in the list is stored in a node, and nodes are linked together in a chain-like structure.
🔸 Types of Linked Lists:
1. Singly Linked List
- Each node contains:
- Data
- Reference to the next node
- The last node points to
null
, indicating the end. - Traversal is one-directional (from head to tail).
2. Doubly Linked List
- Each node contains:
- Data
- Reference to the next node
- Reference to the previous node
- Allows bi-directional traversal.
- Java’s
LinkedList
class is based on this structure.
⚙️ LinkedList Operations in Java
The LinkedList
class provides built-in methods for common operations:
add(E element)
– Add element at the end.addFirst(E element)
/ addLast(E element)
– Insert at beginning or end.remove()
/ removeFirst()
/ removeLast()
– Remove elements.get(int index)
– Access element at a given index (less efficient than array).size()
– Returns the number of elements.
✅ Advantages of LinkedList
- Dynamic Size: Grows or shrinks as needed.
- Efficient Insertions/Deletions: Especially in the middle or ends of the list.
- No memory waste: Unlike arrays, no need to predefine the size.
- Bidirectional Traversal: Possible with a doubly linked list.
❌ Disadvantages of LinkedList
- Slower Random Access: Accessing an element requires traversal from the head or tail.
- Higher Memory Usage: Each node stores additional pointers.
- More Complex Implementation: Compared to arrays.
🔍 LinkedList vs ArrayList
FeatureLinkedListArrayListAccess TimeSlow (O(n))Fast (O(1))Insertion/DeletionFast (especially in middle)Slower (due to shifting)Memory UsageHigher (due to links)LowerData Structure TypeNode-basedDynamic array
🧠 Use Cases of LinkedList
- Implementing queues and stacks
- Real-time systems where frequent insertions/deletions occur
- Applications requiring dynamic resizing with minimal overhead
🏁 Conclusion
The LinkedList
in Java offers a flexible alternative to arrays for dynamic and frequently modified data. By understanding its structure and capabilities, developers can choose the right data structure for their use case and write more efficient, maintainable code.