- 2070 Magh · 5 marks
Insert and delete before a node, singly linked
Short answer
To insert before a key node: if key is the first node, make the new node the new start; otherwise, traverse with prev and cur to link the new node between pred and cur. To delete the node before a key: traverse with two trailing pointers to find the predecessor of the target, skip it, and free it. Both take O(n).
Write algorithms to insert and delete a node before a node in a singly linked list.
Let start point to the first node of a singly linked list of nodes (info, next), and let key be the info value of the given node (the one before which we operate).
Insert a new node before the node with value key
- Allocate
new; setnew->info = x; if allocation fails stop. - If
start == NULL, print "list empty" and stop. - If
start->info == key:new->next = start; start = new;stop. (Insert before first node.) - Set
prev = start,cur = start->next. - While
cur != NULLandcur->info != key:prev = cur; cur = cur->next. - If
cur == NULL, print "key not found" and stop. new->next = cur; prev->next = new;
Before: [prev] -> [cur(key)]
After : [prev] -> [new] -> [cur(key)]
Delete the node before the node with value key
- If
start == NULLorstart->info == key, print "no node before key" and stop. - If
start->next != NULLandstart->next->info == key: the node before key is the first node:t = start; start = start->next; free(t);stop. - Set
prev = start,cur = start->next. - While
cur != NULLandcur->next != NULLandcur->next->info != key:prev = cur; cur = cur->next. - If
cur == NULLorcur->next == NULL, print "key not found" and stop. - Now
curis the node beforekeynode,previs the node beforecur:prev->next = cur->next; free(cur);
Before: [prev] -> [cur] -> [key]
After : [prev] -> [key] (cur freed)
Because a singly list has no prev pointer, we must keep trailing pointers while traversing, so both operations take O(n).
✓ 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×
- Insert before Kth node in doubly linked list · Data Structure and Algorithm, chapter 4
- Delete last node of doubly linked list · Data Structure and Algorithm, chapter 4
- Delete Kth node from doubly linked list · Data Structure and Algorithm, chapter 4
- AVL delete then insert gives same tree? · Data Structure and Algorithm, chapter 6
- Doubly vs singly linked list · Data Structure and Algorithm, chapter 4 · asked 2×
- File system layout; i-node vs linked list · Operating System, chapter 5