Linked List
What is a Linked List?
A linked list is a linear data structure in which elements, called nodes, are connected using pointers. Each node contains two parts: the data and a reference (or pointer) to the next node in the sequence. Unlike arrays, linked lists do not store elements in contiguous memory locations.
Key Characteristics
- Dynamic Size: The size of a linked list can grow or shrink dynamically as nodes are added or removed.
- Non-contiguous Memory Allocation: Nodes are not stored in contiguous memory locations; each node points to the next node.
- Pointer-based Structure: Each node contains a pointer/reference to the next node in the list.
Types of Linked Lists
-
Singly Linked List
- Each node points to the next node.
- The last node points to
null
(orNone
in Python). - Example:
plaintext Head -> [Data|Next] -> [Data|Next] -> [Data|Next] -> null
-
Doubly Linked List
- Each node contains a pointer to both the next and the previous node.
- Provides bidirectional traversal.
- Example:
plaintext Head <-> [Prev|Data|Next] <-> [Prev|Data|Next] <-> [Prev|Data|Next] <-> null
-
Circular Linked List
- The last node points back to the first node, forming a circle.
- Can be singly or doubly linked.
- Example (Singly):
plaintext Head -> [Data|Next] -> [Data|Next] -> [Data|Next] -> Head
Advantages of Linked Lists
- Dynamic Size: Can grow and shrink in size during runtime.
- Ease of Insertion/Deletion: Inserting and deleting nodes does not require shifting elements, unlike arrays.
- Efficient Memory Usage: Memory is allocated as needed.
Disadvantages of Linked Lists
- Memory Overhead: Requires extra memory for pointers.
- Sequential Access: Nodes must be accessed sequentially from the head, making random access inefficient.
- Complexity: More complex to implement and manage compared to arrays.
Applications of Linked Lists
- Dynamic Memory Allocation: Used in applications where dynamic memory allocation is required.
- Implementation of Other Data Structures: Used to implement stacks, queues, and graphs.
- Navigation Systems: Used in navigation systems where items need to be frequently added or removed.