CSC211 ยท 2074 ยท 5 marks
What do you mean by double linked list? Explain with example.
What do you mean by double linked list? Explain with example. [5]
Quick answer
A doubly linked list (also called a two-way linked list) is a linked list in which every node contains three fields: PREV (Left Link) - a pointer that points to the previous node in the list; INFO (Data) - the actual data stored in the node; NEXT (Right Link) - a pointer that points to the next node...
Double Linked List
Definition
A doubly linked list (also called a two-way linked list) is a linked list in which every node contains three fields:
- PREV (Left Link) - a pointer that points to the previous node in the list
- INFO (Data) - the actual data stored in the node
- NEXT (Right Link) - a pointer that points to the next node in the list
The PREV pointer of the first node and the NEXT pointer of the last node both contain NULL.
Node Structure
+--------+--------+--------+
| PREV | INFO | NEXT |
+--------+--------+--------+
In C, the node can be declared as:
struct node {
struct node *prev;
int info;
struct node *next;
};
Diagrammatic Example
Consider a doubly linked list containing three elements: 10, 20, 30
START
|
v
+------+----+------+ +------+----+------+ +------+----+------+
| NULL | 10 | o---+--->| o---| 20 | o---+--->| o---| 30 | NULL |
+------+----+------+ +------+----+------+ +------+----+------+
Node 1 <---+---o Node 2 <---+---o Node 3
- Node 1: PREV = NULL, INFO = 10, NEXT = address of Node 2
- Node 2: PREV = address of Node 1, INFO = 20, NEXT = address of Node 3
- Node 3: PREV = address of Node 2, INFO = 30, NEXT = NULL
Key Characteristics
| Feature | Description |
|---|---|
| Traversal | Can be done in both forward and backward directions |
| PREV of first node | Always NULL |
| NEXT of last node | Always NULL |
| Memory | Requires more memory than singly linked list (extra pointer per node) |
Advantages of Doubly Linked List
- Bidirectional traversal is possible (forward and backward).
- Deletion of a node is easier because we can access the previous node directly without traversing from the beginning.
- Insertion before a given node is simpler compared to singly linked list.
Disadvantage
- Each node requires an extra pointer (PREV), which uses more memory than a singly linked list.
Summary
A doubly linked list allows movement in both directions through the list, making operations like reverse traversal, deletion, and insertion more efficient compared to a singly linked list, at the cost of slightly more memory per node.
Short on time? The 1, 5 and 10 mark versions of this answer, flashcards and practice sets come with a program pass.