- 2072 Magh · 3 marks
Insert before Kth node in doubly linked list
Short answer
Traverse to the Kth node (p). Allocate new node with info x; set new->next = p and new->prev = p->prev. If p->prev != NULL, set p->prev->next = new; else set start = new. Finally p->prev = new.
Write an algorithm to insert an element before Kth node in doubly linked list.
Using the node (prev, info, next), with start pointing to the first node and positions numbered from 1.
Algorithm INSERT_BEFORE_K(start, k, x)
- Allocate a new node
new; if NULL print "overflow" and stop. Setnew->info = x. - Set
p = start; repeat k-1 times:p = p->next. Ifpis NULL (empty list) or becomes NULL, print "invalid position" and stop. Nowpis the K-th node. - Set
new->next = p;new->prev = p->prev. - If
p->prev != NULLthenp->prev->next = new; elsestart = new(K was 1). - Set
p->prev = new.
Before: [a] <-> [p(K)]
After : [a] <-> [new] <-> [p(K)]
The order of the pointer assignments matters: copy p->prev into the new node before overwriting p->prev.
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- Insert and delete kth node in doubly linked list · Data Structure and Algorithm, chapter 4 · asked 2×
- Delete Kth node from doubly linked list · Data Structure and Algorithm, chapter 4
- Insert and delete before a node, singly linked · Data Structure and Algorithm, chapter 4
- Delete last node of doubly linked list · Data Structure and Algorithm, chapter 4