【Leetcode237】Delete Node in a Linked List

没有给定head,唯一的办法就是用next复制一份next,然后把next删掉。如图为了删掉B,先用B复制C,再把C删掉。这里C如果不删掉,会有内存泄漏。题目是删掉B,而B对应的物理空间其实并没有清空,只是在逻辑上删除了:

A     ->        B         ->           C          ->           D

               (C)                 ->                    D

/**
 * 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;
        ListNode* tmp = node->next;
        node->next = node->next->next;
        delete tmp;
    }
};
发布了112 篇原创文章 · 获赞 15 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_39458342/article/details/104737153