- Asked 2/14
- 2073 Bhadra · 5 marks
- 2070 Bhadra · 5 marks
Insert and delete kth node in doubly linked list
Short answer
Insert at kth: traverse to (k-1)th node, set new node's prev and next, link it between (k-1)th and kth; handle head insertion separately. Delete: find kth node, update its predecessor's next and successor's prev, free node; adjust head if needed. O(k) traversal.
How do you insert and delete a node at the kth position of the doubly linked list?
Let start point to the first node of a doubly linked list with nodes (prev, info, next). Positions are numbered 1, 2, 3, ...
struct dnode {
struct dnode *prev;
int info;
struct dnode *next;
};
typedef struct dnode DNODE;
Insert a node at the k-th position (new node becomes the k-th node)
- Allocate
new; if NULL print "no memory" and stop. Setnew->info = x. - If
k == 1:new->prev = NULL; new->next = start;ifstart != NULLthenstart->prev = new;start = new; stop. - Set
p = startand movep = p->next(k-2) times. Ifpis NULL at any point, print "position out of range" and stop. Nowpis the (k-1)-th node. new->next = p->next; new->prev = p;- If
p->next != NULLthenp->next->prev = new. p->next = new.
Before: ... [p] <-> [q] ...
After : ... [p] <-> [new] <-> [q] ...
new->prev = p, new->next = q, q->prev = new, p->next = new
Delete the node at the k-th position
- If
start == NULLprint "underflow" and stop. - Set
p = start; movep = p->next(k-1) times; ifpbecomes NULL print "position out of range" and stop. - If
p->prev != NULLthenp->prev->next = p->next; elsestart = p->next(deleting first node). - If
p->next != NULLthenp->next->prev = p->prev. x = p->info; free(p);
Before: [a] <-> [p] <-> [b]
After : [a] <-> [b] a->next = b, b->prev = a, free(p)
Both operations take O(k) time for traversal; the pointer change itself is O(1). Special cases to remember: first node, last node, and a one-node list.
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- Insert before Kth node in doubly linked list · Data Structure and Algorithm, chapter 4
- 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
- Delete employee from doubly linked list · Data Structure and Algorithm, chapter 4
- AVL delete then insert gives same tree? · Data Structure and Algorithm, chapter 6