leetcode237题 题解 翻译 C语言版 Python版

237. Delete Node in a Linked List

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.

237.删除链表中的结点

写一个函数来删除一个单链表中的结点(非尾结点),而且只给出那个结点的地址。

假设一个链表如1->2->3->4,然后给你第三个结点,也就是值为3的那个结点。那么在你调用你的函数后你的链表应该变成1->2->4.


思路:传统删除链表中某个结点必须记录下一个结点,这样才能将链表重新连接。但这里链表是单向的,从当前准备被删的结点无法追溯到上一个结点。这里可以变通地考虑,既然这个结点是准备要删的,那么这个结点的值就已经无用了。我们就可以把下一个结点的值移到当前结点上,把问题转化为删除下一个结点,即1->2->3->4变成1->2->4->4,再删除第四个结点,变成1->2->4.

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
void deleteNode(struct ListNode* node) {
    node->val = node->next->val;
    node->next = node->next->next;
}



# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def deleteNode(self, node):
        """
        :type node: ListNode
        :rtype: void Do not return anything, modify node in-place instead.
        """
        node.val = node.next.val
        node.next = node.next.next


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值