Skip to main content

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)

  1. Allocate new; if NULL print "no memory" and stop. Set new->info = x.
  2. If k == 1: new->prev = NULL; new->next = start; if start != NULL then start->prev = new; start = new; stop.
  3. Set p = start and move p = p->next (k-2) times. If p is NULL at any point, print "position out of range" and stop. Now p is the (k-1)-th node.
  4. new->next = p->next; new->prev = p;
  5. If p->next != NULL then p->next->prev = new.
  6. 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

  1. If start == NULL print "underflow" and stop.
  2. Set p = start; move p = p->next (k-1) times; if p becomes NULL print "position out of range" and stop.
  3. If p->prev != NULL then p->prev->next = p->next; else start = p->next (deleting first node).
  4. If p->next != NULL then p->next->prev = p->prev.
  5. 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)

All Data Structure and Algorithm chapter 4 questions →