LeetCode 237: Delete Node in a Linked List

Linked List

Problem Description

Explanation:

To delete a node from a singly-linked list without knowing the head node, we can follow these steps:

  1. Copy the value from the next node to the current node.
  2. Update the current node's next pointer to skip the next node.

This way, we effectively "delete" the given node by overwriting its value and changing the next pointer to skip the next node.

Time complexity: O(1)
Space complexity: O(1)

:

Solutions

class ListNode {
    int val;
    ListNode next;
    ListNode(int x) { val = x; }
}

public void deleteNode(ListNode node) {
    node.val = node.next.val;
    node.next = node.next.next;
}

Loading editor...