Insert a new node holding value at position index (0-based) and return the head.
Index 0 inserts at the front. If index is at or beyond the list length, append
at the end.
insertNode(head, index, value)
Input format: list | index | value. Output the resulting list,
space-separated.
(1 → 2 → 3), index 1, value 9 // → 1 → 9 → 2 → 3
(1 → 2 → 3), index 0, value 9 // → 9 → 1 → 2 → 3
(1 → 2 → 3), index 5, value 9 // → 1 → 2 → 3 → 9
Inserting a node has the same structural challenge as removing one: to splice a new node in before a position, you need a handle on the node that will sit just before it. And just like removal, inserting at position zero has no natural predecessor within the original list — another case for a dummy node.
Placing a placeholder before the real head means position zero stops being special: inserting "before the original head" becomes the same operation as inserting after any other node — right after the dummy. The walk-to-position-then-splice logic stays uniform regardless of whether the target is the front, the middle, or past the end.
next at previous.next first — before touching previous.next — then point previous.next at the new node.next.If you set previous.next to the new node before wiring the new node's own next, you'd overwrite your only reference to the rest of the list, losing everything after the insertion point. Wiring the new node's outgoing pointer first, while the old chain is still intact, is what makes the splice safe.
Inserting into an empty list, at the front, in the middle, or past the end are all, mechanically, "walk previous some number of steps (possibly zero, possibly capped by running out of list), then splice." No case needs bespoke logic.
The walk touches at most index nodes (or the whole list, if the index exceeds it), so work is linear in the requested position, with only a small constant number of pointers needed regardless of list size.
def insert_node(head, index, value):
dummy = ListNode(0)
dummy.next = head
prev = dummy
i = 0
while i < index and prev.next is not None:
prev = prev.next
i += 1
node = ListNode(value)
node.next = prev.next
prev.next = node
return dummy.next
Sign in to join the discussion.
No comments yet. Be the first to ask a question.
Press Run to execute your code, or Submit to test and complete this problem.