Delete Node in a LinkedList

Linked List

easy

If we want to delete the given node directly, we need to know the previous node. Obviously, we cannot get such information. Thus we copy the value of the next node to the current node and delete the next node.

/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public void deleteNode(ListNode node) {
node.val = node.next.val;
node.next = node.next.next;
}
}