PPractick

DSA interview question

Insert a Node in a Linked List (at the Head and at a Position)

Easy · Data structures · Topics: linkedlist

The problem

The music player's "play next" button puts a song at the front of the queue, and "insert at position k" drops a song into a specific slot. With an array, both shift every later element. With a singly linked list, inserting at the head is O(1): create a node whose next is the old head, and it becomes the new head. Inserting at position k needs a walk to the node just before position k, then two pointer assignments. The order of those two assignments is where bugs hide.

Example: list 2 -> 3, insert 1 at the head → 1 -> 2 -> 3.

Function signature

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

Test cases

InputOutput listExplanation
insertAtHead(2 -> 3, 1)1 -> 2 -> 3The new node becomes the head
insertAtHead(empty, 5)5Inserting into an empty list
insertAtHead(7, 7)7 -> 7
insertAtPosition(1 -> 2 -> 4, 3, 3)1 -> 2 -> 3 -> 4In the middle
insertAtPosition(1 -> 2, 1, 0)0 -> 1 -> 2Position 1 is the head
insertAtPosition(1 -> 2, 3, 9)1 -> 2 -> 9Position length + 1 is the tail

(Confirm: positions are 1-indexed and valid; the function returns the (possibly new) head.)

How interviewers phrase it

Clarifying questions to ask

  1. Is the position 0-indexed or 1-indexed? What if it's out of range?
  2. Should the function return the new head? (It must, for head insertions.)
  3. Is a tail pointer available? (Makes tail insertion O(1).)

Follow-ups to expect

  1. "Why must the new node's next be set before changing the predecessor?"
  2. "Why return the head?"
  3. "How would a dummy head help?"
  4. "What's the cost of inserting at the tail?"
  5. "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