Delete the linked list node in O(1) time

Delete the linked list node in O(1) time


from acwing 28
Time limit:1s
Memory limit:64MB

Problem Description

Given a node pointer of a singly linked list, define a function to delete the node in O(1) time.

Assume that the linked list must exist, and the node must not be the tail node.

Sample:

输入:链表 1->4->6->8
      删掉节点:第2个节点即6(头节点为第0个节点)
输出:新链表 1->4->8
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
    
    
public:
    void deleteNode(ListNode* node) {
    
    
        
    }
};

This topic is a very simple topic, but we need to think of a thought.

For the problem of deleting a specified node, our thinking after learning the linked list may be to point the previous node of the node directly to the next node of the node.

As shown in the figure:

Insert picture description here

If you want to delete node 02, the first thing you might think of is to point 01 to 03 as shown by the dotted line in the figure.

But for this topic, there is no head node, and it is a one-way non-circular linked list. We cannot get the previous node. Therefore, we cannot delete the current node, but delete the next node.
Assign the value of the 03 node to 02:

	node->val = node->next->val;		//node表示当前节点

Delete 03 again, here is the same idea as we mentioned earlier, we know the previous node 02 of node 03

	node->next = node->next->next;		//node表示当前节点
解释:
原来:01 -> 02 -> 03
操作1:01 -> 03 -> 03
操作2:01 -> 03

The ac code only needs to connect the above two operations together.

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

Guess you like

Origin blog.csdn.net/qq_45985728/article/details/114099342