Leetcode 237. Delete Node in a Linked List

Lintcode 372. 在O(1)时间复杂度删除链表节点

Posted by Olivia Liu on November 3, 2019 | 阅读:

Description

Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.

给定一个单链表中的一个等待被删除的节点(非表头或表尾)。请在在 O(1) 时间复杂度删除该链表节点。

Note: 1 ≤ mn ≤ length of list.

Examples

Input: head = [4,5,1,9], node = 5
Output: [4,1,9]
Explanation: You are given the second node with value 5, the linked list should become 4 -> 1 -> 9 after calling your function.
Input: head = [4,5,1,9], node = 1
Output: [4,5,9]
Explanation: You are given the third node with value 1, the linked list should become 4 -> 5 -> 9 after calling your function.

Answer

Create a new node to represent the next node of the input and let the input node to be its next node.

Time Complexity

O(1)

Code

C++

class Solution {
public: 
    void deleteNode(ListNode* node) {
        if(!node || !node->next) return;
        
        ListNode* dummy = node->next;
        node->val = dummy->val;
        node->next = dummy->next;
    }
};