Skip to main content

Doubly linked list: bank customer records

Short answer

To delete customer 00056PR, locate its node p. Update links: if not first, set p->prev->next = p->next else start = p->next; if p->next exists, set p->next->prev = p->prev; free(p). For sorted insertion, find insertion point after p, link new node between p and p->next. Doubly deletion uses prev directly, avoiding a trailing pointer needed in a singly list.

Suppose you have a doubly linked list that stores bank customers information. Explain how a customer with account number 00056PR can be deleted and how a new customer can be inserted. What is the difference in this implementation relative to singly linked list?

Assume each node stores the customer data and the list is kept sorted by account number:

struct cust {
    struct cust *prev;
    char acc[10];          /* e.g. "00056PR" */
    char name[30];
    float balance;
    struct cust *next;
};

start points to the first node.

Deleting customer 00056PR

  1. If start == NULL, print "list empty" and stop.
  2. Set p = start; while p != NULL and strcmp(p->acc, "00056PR") != 0, set p = p->next.
  3. If p == NULL, print "customer not found" and stop.
  4. If p->prev != NULL, set p->prev->next = p->next; otherwise (first node) start = p->next.
  5. If p->next != NULL, set p->next->prev = p->prev.
  6. free(p).
Before: [A] <-> [00056PR] <-> [B]
After : [A] <-> [B]      A->next = B, B->prev = A

Inserting a new customer (kept in sorted order)

  1. Allocate node new and fill its data.
  2. If the list is empty or strcmp(new->acc, start->acc) < 0: new->prev = NULL; new->next = start; if start != NULL then start->prev = new; start = new; stop.
  3. Else find p, the last node whose account number is smaller than the new one: p = start; while (p->next != NULL && strcmp(p->next->acc, new->acc) < 0) p = p->next;
  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]

Difference from a singly linked list

PointDoublySingly
Delete found nodeUses p->prev directlyNeeds a trailing pointer prev kept during search
InsertSet 4 links (new->prev, new->next, p->next, q->prev)Set 2 links
MemoryExtra pointer per customerLess
Search directionCan search from either endOnly forward

So a doubly list makes deletion simpler (no trailing pointer) but needs two extra pointer updates and more memory.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Data Structure and Algorithm chapter 4 questions →