[The sword refers to the offer brushing the question] AcWing 28. Delete the linked list node in O(1) time

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;
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326215751&siteId=291194637
Recommended