leetcode 237 删除链表节点

很有意思的一道题,需要你删除链表中的一个节点,并且只给你了这个节点,你在不知道前一个节点地址或者头结点地址的情况下如何解决这个问题。

通过把该节点下一个节点的值赋给自己,然后删除下一个节点,就完成了。虽然简单,但是思路与之前做的题有所不同,有一定的价值。

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

 或者可以更直白,直接把下一个节点的值浅拷贝到该节点,val与next值同时赋值,更简洁。

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     void deleteNode(ListNode* node) 
12     {
13         *node = *node->next;        
14     }
15 };

 

posted @ 2021-03-13 17:50  zhaohhhh  阅读(45)  评论(0)    收藏  举报