Skip to main content

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

  1. If start == NULL, print "underflow (list empty)" and stop.
  2. Set p = start; while p->next != NULL, set p = p->next. Now p is the last node.
  3. If p->prev == NULL (only one node): set start = NULL. Else: set p->prev->next = NULL (second-last node becomes the last).
  4. 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)

All Data Structure and Algorithm chapter 4 questions →