【LeetCode】237. Delete Node in a Linked List(链表)

Question

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

Supposed the linked list is 1 -> 2 -> 3 -> 4 and you are given the third node with value 3, the linked list should become 1 -> 2 -> 4 after calling your function.

Analyze

思路:用当前节点的下一个节点覆盖掉当前节点,之后释放下一个节点的内存空间。

这个方案不是直接的删除该节点,而需要间接来做。

因为,如果想直接删除该节点,由于上一个节点的next指向当前节点,我们需要把上一个节点的next修改为当前节点的next。然而我们并无法访问到上一个节点,也就无法对其next进行修改。故直接删除是不可行的。

也就是说,对于A->B->C->null,表面上我们是删除了B节点,实际上释放的是C节点的空间。

My code

/**
 * 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) {
        if (node) {
            //move the next node to current position,then delete the next node
            //with this, we can delete the current node
            ListNode* nxt = node->next;
            node->val = nxt->val;
            node->next = nxt->next;
            delete nxt;
        }
    }
};

More

本题目不考虑尾节点的删除,同时由于题目的特殊背景,也并不涉及删除头节点引发的问题。

如果更一般性的,我们应该注意一些边界问题:

  1. 空节点;

  2. 尾节点;

  3. 头节点的删除可能会影响到head指针

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值