Leetcode 237. Delete Node in a Linked List
You are given a node in a linked list (not the tail node). Write a method to delete this node.
The node is guaranteed not to be the last node and will always be a valid node of the linked list.
You will not be given access to the head of the linked list, instead you will be given access to the node to be deleted directly.
Let’s look at the function signature:
public class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
public void deleteNode(ListNode node) {
// your code here
}
next
pointer.next
pointer of the current node to the node after the next node.public class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
public void deleteNode(ListNode node) {
// Given node is not the tail and is always valid
// Copy the next node's value to the current node
node.val = node.next.val;
// Bypass the next node
node.next = node.next.next;
}
By copying the value from the next node to the current node and bypassing the next node, we effectively delete the current node without needing access to the head of the list. This is efficient and meets the constraints of the problem.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?