{
  "slug": "linked-list-insert",
  "title": "Insert into a Linked List",
  "category": "Linked Lists",
  "difficulty": "easy",
  "complexity": {
    "time": "O(1) at a known node",
    "space": "O(1)"
  },
  "idea": "Inserting into a list only changes pointers: the new node points to the old next, and the previous node points to the new one. Unlike an array, no elements move — but you must walk to the position first.",
  "code": [
    "walk to the node before position p",
    "newNode.next = prev.next",
    "prev.next = newNode"
  ],
  "example": {
    "array": [
      7,
      3,
      9,
      4
    ],
    "target": 5,
    "at": 2
  },
  "invariant": "Each step is the real data structure at that step — the picture is a pure function of it.",
  "stepCount": 4,
  "steps": [
    {
      "i": 0,
      "op": "say",
      "caption": "Insert 5 at position 2.",
      "note": null,
      "codeLine": 1,
      "stats": null,
      "array": [
        7,
        3,
        9,
        4
      ],
      "focus": [
        null,
        null,
        null,
        null
      ],
      "markers": [
        {
          "name": "head",
          "index": 0,
          "tone": "bound"
        }
      ],
      "regions": []
    },
    {
      "i": 1,
      "op": "read",
      "caption": "Walk to node 1 — the node whose pointer we will rewire.",
      "note": null,
      "codeLine": 1,
      "stats": null,
      "array": [
        7,
        3,
        9,
        4
      ],
      "focus": [
        null,
        "read",
        null,
        null
      ],
      "markers": [
        {
          "name": "head",
          "index": 0,
          "tone": "bound"
        },
        {
          "name": "prev",
          "index": 1,
          "tone": "pivot"
        }
      ],
      "regions": []
    },
    {
      "i": 2,
      "op": "insert",
      "caption": "Link 5 in: it points to the old node, and the previous node points to it.",
      "note": null,
      "codeLine": 3,
      "stats": null,
      "array": [
        7,
        3,
        5,
        9,
        4
      ],
      "focus": [
        null,
        null,
        "insert",
        null,
        null
      ],
      "markers": [
        {
          "name": "head",
          "index": 0,
          "tone": "bound"
        },
        {
          "name": "prev",
          "index": 1,
          "tone": "pivot"
        }
      ],
      "regions": []
    },
    {
      "i": 3,
      "op": "settle",
      "caption": "Done — splicing 5 in cost exactly two pointer changes.",
      "note": null,
      "codeLine": 3,
      "stats": null,
      "array": [
        7,
        3,
        5,
        9,
        4
      ],
      "focus": [
        null,
        null,
        "settled",
        null,
        null
      ],
      "markers": [
        {
          "name": "head",
          "index": 0,
          "tone": "bound"
        }
      ],
      "regions": []
    }
  ]
}