- 2074 Bhadra · 5 marks
Delete last node of doubly linked list
Short answer
Move a pointer p to the last node by following next until p->next is NULL. If p->prev is NULL (only one node), set start to NULL; else set p->prev->next = NULL. Store p->info, free(p), return the value. Finding the last node takes O(n) unless a rear pointer is used.
How do you delete a node at the end of the doubly linked list?
Let start point to the first node of a doubly linked list.
struct dnode {
struct dnode *prev;
int info;
struct dnode *next;
};
typedef struct dnode DNODE;
Algorithm
- If
start == NULL, print "underflow (list empty)" and stop. - Set
p = start; whilep->next != NULL, setp = p->next. Nowpis the last node. - If
p->prev == NULL(only one node): setstart = NULL. Else: setp->prev->next = NULL(second-last node becomes the last). x = p->info; free(p);return x.
Before: start -> [a] <-> [b] <-> [p]
After : start -> [a] <-> [b] -> NULL (p freed)
b->next = NULL
int delete_end(DNODE **start) {
DNODE *p = *start; int x;
if (p == NULL) { printf("Underflow\n"); return -1; }
while (p->next != NULL) p = p->next; /* go to last node */
if (p->prev == NULL) *start = NULL; /* only one node */
else p->prev->next = NULL;
x = p->info;
free(p);
return x;
}
Finding the last node takes O(n); the prev pointer removes the need for a trailing pointer that a singly list requires. If a rear pointer is kept, deletion is O(1).
✓ 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
- Insert before Kth node in doubly linked list · Data Structure and Algorithm, chapter 4
- Delete employee from doubly linked list · Data Structure and Algorithm, chapter 4
- Doubly linked list: bank customer records · Data Structure and Algorithm, chapter 4
- File system layout; i-node vs linked list · Operating System, chapter 5