CSC211 ยท 2081 ยท 5 marks
What is the algorithm for node insertion and deletion from specified position from doubly linked list.
What is the algorithm for node insertion and deletion from specified position from doubly linked list. [5]
Data Structures and AlgorithmsChapter 5: ListsBasic operations in Linked List
Quick answer
In a doubly linked list, each node has three fields: prev, info, and next.
Node Insertion and Deletion at Specified Position in Doubly Linked List
Insertion at Specified Position in Doubly Linked List
Algorithm
Algorithm: Insert a node at a specified position in a doubly linked list
Input: Position (pos), Data (val)
Steps:
- Create a new node and set
newnode->info = val - If
head = NULL, then:- Set
newnode->next = NULL - Set
newnode->prev = NULL - Set
head = newnode - Exit
- Set
- If
pos = 1(insert at beginning), then:- Set
newnode->next = head - Set
newnode->prev = NULL - Set
head->prev = newnode - Set
head = newnode - Exit
- Set
- Else, traverse to the specified position:
- Set
temp = head - Set
count = 1 - While
count < pos - 1andtemp != NULL:temp = temp->nextcount = count + 1
- End While
- Set
- If
temp = NULL, then print "Position out of range" and Exit - Set
newnode->next = temp->next - Set
newnode->prev = temp - If
temp->next != NULL, then:- Set
temp->next->prev = newnode
- Set
- Set
temp->next = newnode - End
Deletion at Specified Position in Doubly Linked List
Algorithm
Algorithm: Delete a node from a specified position in a doubly linked list
Input: Position (pos)
Steps:
- If
head = NULL, then print "Empty list" and Exit - Set
temp = head - If
pos = 1(delete from beginning), then:- Set
hold = head - Set
head = head->next - If
head != NULL, then sethead->prev = NULL - Free
(hold) - Exit
- Set
- Else, traverse to the specified position:
- Set
count = 1 - While
count < posandtemp != NULL:temp = temp->nextcount = count + 1
- End While
- Set
- If
temp = NULL, then print "Position out of range" and Exit - Set
hold = temp - If
temp->prev != NULL, then:- Set
temp->prev->next = temp->next
- Set
- If
temp->next != NULL, then:- Set
temp->next->prev = temp->prev
- Set
- Free
(hold) - End
Diagram Illustration
Before Insertion at position 2:
[NULL|10|-->] <--> [-->|20|-->] <--> [-->|30|NULL]
After Inserting 15 at position 2:
[NULL|10|-->] <--> [-->|15|-->] <--> [-->|20|-->] <--> [-->|30|NULL]
Key Point: In a doubly linked list, both the
nextpointer of the previous node and theprevpointer of the next node must be updated during insertion and deletion to maintain bidirectional linkage.
Short on time? The 1, 5 and 10 mark versions of this answer, flashcards and practice sets come with a program pass.