Insertion before the value X in Linked List

Pattern: Traversal and dummy nodes

easy

Walk with prev from a dummy node, looking one node ahead. When prev.next holds X, link the new node in between. If X never appears, nothing changes.

The problem

Given the head of a singly linked list and two values X and val, insert a new node holding val just before the node holding X, and return the head. X appears at most once; if it does not appear, return the list unchanged. For example, 1 → 2 → 3 with X = 2, val = 5 becomes 1 → 5 → 2 → 3, and 1 with X = 1, val = 10 becomes 10 → 1.

The function name insertBeforeX matches the takeUforward practice page. Use the link above for the exact statement and limits.

Think first

  • Inserting before a node needs which other node?
  • How do you know the next node holds X while you still stand before it?
  • What if X is in the head?

Hints

    Brute force, and why it fails

    Find X with one walk and its previous node with another: O(n) either way, but twice the walking. Looking one node ahead does it in one pass.

    The key insight

    "Before X" becomes "after the node whose next is X". Looking one node ahead gives you that node at the moment you find X.

    Dry run

    dummy0prev
    11 
    22 
    33 

    The list is 1 → 2 → 3, X = 2 and val = 5. prev starts on a dummy before the head.

    Step 1 of 4

    The plan

    dummy.next = head, prev = dummy
    while prev.next is not null:
        if prev.next.val == X:
            prev.next = new node(val, next = prev.next)
            stop
        prev = prev.next
    return dummy.next
    

    Complexity

    Time
    O(n)
    Space
    O(1)

    One walk, stopping at X or the end.

    Edge cases

    • X in the head: the new node becomes the head.
    • X absent or the list empty: unchanged.
    • X in the tail: the new node goes second to last.
    I've built my logic, show the code

    Java

    class Solution {
        public ListNode insertBeforeX(ListNode head, int X, int val) {
            ListNode dummy = new ListNode(0);       // so inserting before the head needs no special case
            dummy.next = head;
            for (ListNode prev = dummy; prev.next != null; prev = prev.next) {
                if (prev.next.val == X) {
                    ListNode node = new ListNode(val);
                    node.next = prev.next;
                    prev.next = node;
                    break;                          // only before the first X
                }
            }
            return dummy.next;
        }
    }

    C++

    class Solution {
    public:
        ListNode* insertBeforeX(ListNode* head, int X, int val) {
            ListNode dummy(0);                      // so inserting before the head needs no special case
            dummy.next = head;
            for (ListNode* prev = &dummy; prev->next != NULL; prev = prev->next) {
                if (prev->next->val == X) {
                    ListNode* node = new ListNode(val);
                    node->next = prev->next;
                    prev->next = node;
                    break;                          // only before the first X
                }
            }
            return dummy.next;
        }
    };

    Python

    from lib import ListNode
    
    class Solution:
        def insertBeforeX(self, head: ListNode, X: int, val: int) -> ListNode:
            dummy = ListNode(0, head)               # so inserting before the head needs no special case
            prev = dummy
            while prev.next is not None:
                if prev.next.val == X:
                    prev.next = ListNode(val, prev.next)
                    break                           # only before the first X
                prev = prev.next
            return dummy.next

    Common mistakes

    • Checking prev.val == X, which inserts after X instead of before.
    • Inserting before every copy when only one should get it.
    • Returning head when a new head was inserted.

    Similar problems