PPractick

DSA interview question

Insert a Node Before the Head of a Doubly Linked List

Easy · Data structures · Topics: linkedlist, doubly linkedlist

The problem

The browser from the previous problem keeps its history as a doubly linked list, and opening a page from a "recently closed" menu inserts it at the front. In a doubly linked list, inserting before the head means wiring two links instead of one: the new node's next points to the old head, and the old head's prev points back to the new node. Forgetting the second link is the classic bug, and it only shows up when you traverse backwards. The same two-sided wiring applies when inserting at any position.

Example: 2 <-> 3, insert 1 before the head → 1 <-> 2 <-> 3.

Function signature

DNode* insertBeforeHead(DNode* head, int x);             // returns the new head
DNode* insertAtPosition(DNode* head, int pos, int x);    // 1-indexed, 1 <= pos <= length + 1

Test cases

InputForward resultExplanation
insertBeforeHead(2 <-> 3, 1)1 <-> 2 <-> 3Backward: 3 <-> 2 <-> 1
insertBeforeHead(empty, 5)5
insertBeforeHead(7, 7)7 <-> 7
insertAtPosition(1 <-> 2 <-> 4, 3, 3)1 <-> 2 <-> 3 <-> 4Four links change
insertAtPosition(1 <-> 2, 1, 0)0 <-> 1 <-> 2Same as inserting before the head
insertAtPosition(1 <-> 2, 3, 9)1 <-> 2 <-> 9At the tail

(Confirm: after every insertion, the backward traversal must be the exact reverse of the forward one.)

How interviewers phrase it

Clarifying questions to ask

  1. Is the position 0- or 1-indexed?
  2. Should the function return the new head?
  3. Is there a tail pointer to maintain as well?

Follow-ups to expect

  1. "How many pointers change when inserting in the middle?"
  2. "What happens if you forget oldHead->prev = newNode?"
  3. "How do you verify a doubly linked list?"
  4. "Complexity?"

Practise questions like this with a real engineer

On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.

Book a free mock interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in