Category: Brain Teasers
Deleting the current node means overwriting the current node with the data of the next node and deleting the next node
topic
Given a node pointer in a singly linked list, define a function to delete the node in O(1) time.
It is assumed that the linked list must exist, and the node must not be a tail node.
Sample
Input: linked list 1->4->6->8
Delete node: the second node is 6 (the head node is the 0th node)
Output: new linked list 1->4->8
java code
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public void deleteNode(ListNode node) {
node.val = node.next.val;
node.next = node.next.next;
}
}