237. Delete Node in a Linked List
EasyView on LeetCode
Time: O(1)
Space: O(1)
Problem Overview
You don't have the previous node, but you have the node to delete.
Intuition
You don't have the previous node, but you have the node to delete. Copy the value from the next node into the current node, then skip the next node. The current node effectively becomes the next node.
Algorithm
- 1node.val = node.next.val.
- 2node.next = node.next.next.
Example Walkthrough
Input: head = [4,5,1,9], node = 5
- 1.Copy 1 (next's val) into node. node.next = node.next.next (skip old "1" node).
- 2.List: [4,1,9].
Output: [4,1,9]
Common Pitfalls
- •This only works because the problem guarantees node is not the tail.
237.cs
C#
// Approach: We are not given the head, so standard deletion by relinking from the previous node is impossible.
// Instead, copy the next node's value into the current node and skip the next node.
// node.val = node.next.val; node.next = node.next.next;
// This effectively 'moves' the next node into the current position, achieving the same observable effect.
// Guaranteed by the problem: the node to delete is never the tail node.
// Time: O(1) Space: O(1).
public class ListNode
{
public int val;
public ListNode next;
public ListNode(int x) { val = x; }
}
public class Solution
{
public void DeleteNode(ListNode node)
{
if (node.next != null)
{
node.val = node.next.val;
node.next = node.next.next;
}
}
}Was this solution helpful?
Related Problems
- 19. Remove Nth Node From End of List(Medium)
- 25. Reverse Nodes in k-Group(Hard)
- 61. Rotate List(Medium)
- 86. Partition List(Medium)
- 92. Reverse Linked List II(Medium)
- 114. Flatten Binary Tree to Linked List(Medium)