Delete Node in a Linked List

Remove a node from a linked list when you are handed only that node and not the head.

A singly linked list holds some numbers. You get a reference to one of its nodes, node, and nothing else, so you cannot start from the beginning of the list. node is never the last node. Delete it: afterwards, reading the list from its first node must give the same values in the same order, minus the value of node, and the list must be one node shorter.

Example 1
Input: head = [4, 5, 1, 9], node = 5
Output: [4, 1, 9]
Example 2
Input: head = [4, 5, 1, 9], node = 1
Output: [4, 5, 9]
Solution

The Idea

A linked list stores its values in separate objects called nodes, such as the four nodes holding 4, 5, 1 and 9. Each node keeps one value and a link, named next, to the node after it. The 9 has no node after it, so its next is null. The first node is called the head. In a singly linked list the links point one way only, from each node to the one after it.

How would you normally take 5 out of the list 4, 5, 1, 9? You would change the link of the node before it. The 4 would point straight at 1, and a walk from the head would no longer meet 5. Here, though, you are handed only the node holding 5. From it you can follow next to 1 and then to 9, but no link leads back to 4.

So how can a node leave the list when the link that leads to it cannot be changed? Think about what the list is to anyone who reads it: the values met on a walk from the head, in order. Nobody can tell which node object carries which value. So the node holding 5 does not have to leave. It can take over the value of the node after it, and then that next node is the one taken out. Its link comes from the node we hold, so we can change it. Look at the picture below.

The list 4, 5, 1, 9 with node on 5 and node.next on 1. Step 1 copies the next value, 1, into node, giving 4, 1, 1, 9. Step 2 points node past the next node straight to 9, so the list reads 4, 1, 9 and the old node holding 1 leaves the list.

In the row labelled start, node is on 5 and node.next is on 1. The head, 4, is not given to us. In the row labelled 1. copy the next value, node now holds 1 as well, so the list reads 4, 1, 1, 9 for a moment. In the row labelled 2. skip the next node, the link of node jumps over the grey node straight to 9. A walk from the head now gives 4, 1, 9, the output of Example 1.

The value 5 is gone, yet the node object that left the list is the one that held 1. This also shows why node may not be the last node: the last node has no next node to copy from.

Solution Approach

Turning that idea into code means settling three things: why the node itself has to change, in which order its two fields change, and what goes wrong on the last node.

Changing the node, not a variable

Could the method simply move node along, with node = node.next? No. In Java, the parameter node is the method's own copy of a reference, the handle Java uses to reach the node object. Pointing that copy somewhere else changes no link in the list. Only assigning to the fields of the object, node.val and node.next, changes what a walk from the head sees.

Copying first, then unlinking

Which field changes first? The value has to be copied while node.next still leads to the node holding 1. If the link changed first, node.next would already be the node holding 9, and the copy would give 4, 9, 9 instead of 4, 1, 9. So the method copies node.next.val into node.val, then sets node.next to node.next.next.

Why the last node is ruled out

What if node were the 9? Its next is null, so reading node.next.val throws a NullPointerException and the list is left unchanged. No other trick helps either. Removing the last node means setting the next of the node before it to null, and that node cannot be reached. This is why the problem promises that node is never the last node.

Java Solution

The method deleteNode works in these steps:

  1. First, copy the value of the next node into the given node with node.val = node.next.val. Both nodes now hold the same value.
  2. Then unlink the next node with node.next = node.next.next, so node links straight to the node after it.
  3. The method returns nothing, because the list was changed in place, so any code holding the head sees the shorter list.

Next to the method, the class has a small ListNode class and three helpers: build makes a list from values, find returns the node holding a value, and show prints a list like [4, 1, 9]. The main method runs both examples and deletes the head of the two-node list [7, 3]. Then it runs Example 1 again with two extra variables, five and one, kept on the nodes that held 5 and 1.

Java
public class DeleteNodeInLinkedList {

    static class ListNode {
        int val;
        ListNode next;
        ListNode(int val) { this.val = val; }
    }

    public static void deleteNode(ListNode node) {
        node.val = node.next.val;     // take over the next node's value
        node.next = node.next.next;   // and unlink the next node
    }

    static ListNode build(int... values) {
        ListNode dummy = new ListNode(0);
        ListNode tail = dummy;
        for (int v : values) {
            tail.next = new ListNode(v);
            tail = tail.next;
        }
        return dummy.next;
    }

    static ListNode find(ListNode head, int value) {
        while (head.val != value) {
            head = head.next;
        }
        return head;
    }

    static String show(ListNode node) {
        StringBuilder sb = new StringBuilder("[");
        for (; node != null; node = node.next) {
            sb.append(node.val).append(node.next != null ? ", " : "");
        }
        return sb.append("]").toString();
    }

    public static void main(String[] args) {
        ListNode head = build(4, 5, 1, 9);
        deleteNode(find(head, 5));
        System.out.println(show(head));

        head = build(4, 5, 1, 9);
        deleteNode(find(head, 1));
        System.out.println(show(head));

        head = build(7, 3);
        deleteNode(head);             // the first node of a two-node list
        System.out.println(show(head));

        head = build(4, 5, 1, 9);
        ListNode five = find(head, 5);
        ListNode one = find(head, 1);
        deleteNode(five);
        System.out.println(show(head) + "  five.val = " + five.val
                + ", one.val = " + one.val + ", one.next.val = " + one.next.val);
    }
}

Running it prints:

Output
[4, 1, 9]
[4, 5, 9]
[3]
[4, 1, 9]  five.val = 1, one.val = 1, one.next.val = 9

The second line, [4, 5, 9], is Example 2: the node that held 1 took the value 9 and dropped the old last node. On the third line, [3], the given node was the head itself. It now holds 3, so the head variable in main still leads to the right list.

Look at the last line. five.val = 1 shows that the node object which held 5 is still in the list, now holding 1. The node one still holds 1 and still links to 9, as one.next.val = 9 shows. But no link in the list leads to it any more, so a walk from the head never meets it.

Both wrong versions described earlier fail as expected when run on Example 1. A method whose body is only node = node.next leaves the list as [4, 5, 1, 9], and swapping the two lines of deleteNode gives [4, 9, 9].

Complexity

The method does the same two assignments however long the list is.

  • Time: O(1). It never walks the list or searches for the node before node. It reads one neighbour and rewrites two fields of the given node.
  • Space: O(1). No new node is created. The removed node is simply no longer linked from the list.

When you have the head and a position to remove, see Remove Nth Node From End of List.