Doubly Linked List
Doubly Linked List
A Doubly Linked List (DLL) is a type of linked list in which each node contains:
Data
A pointer to the next node (next)
A pointer to the previous node (prev)
The purpose of a doubly linked list is to enable both-way traversal while still
allowing non-contiguous memory storage. Just like a singly linked list, we need to
have a starting pointer pointing to the first node. The last node in the list points to
NULL.
Node Structure
Pseudocode:
struct Node
{
int data; //The data point
struct Node *Prev; //Pointer to the previous node
struct Node *Next; //Pointer to the next node
};
Operations on a Doubly Linked List
1. Insert at the Beginning
Pseudocode:
Function insertAtBeginning(data):
newNode ← Create a new node with data
newNode.next ← head
if head ≠ NULL:
head.prev ← newNode
head ← newNode
Pseudocode:
Function insertAtEnd(data):
newNode ← Create a new node with data
if head = NULL:
head ← newNode
return
temp ← head
while temp.next ≠ NULL:
temp ← temp.next
temp.next ← newNode
newNode.prev ← temp
Pseudocode:
Pseudocode:
Function deleteFromBeginning():
if head = NULL:
print "List is empty"
return
head ← head.next
if head ≠ NULL:
head.prev ← NULL
5. Delete from the End
Pseudocode:
Function deleteFromEnd():
if head = NULL:
print "List is empty"
return
temp ← head
while temp.next ≠ NULL:
temp ← temp.next
if temp.prev ≠ NULL:
temp.prev.next ← NULL
else:
head ← NULL
Pseudocode:
Function deleteAtPosition(pos):
if head = NULL:
print "List is empty"
return
temp ← head
for i ← 1 to pos:
if temp = NULL:
print "Position out of range"
return
temp ← temp.next
if temp.prev ≠ NULL:
temp.prev.next ← temp.next
if temp.next ≠ NULL:
temp.next.prev ← temp.prev
7. Display Forward
Function displayForward():
temp ← head
while temp ≠ NULL:
print temp.data
temp ← temp.next
8. Display Reverse
Function displayReverse():
temp ← head
while temp.next ≠ NULL:
temp ← temp.next
while temp ≠ NULL:
print temp.data
temp ← temp.prev