• [LeetCode] 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.

    问题:只给定单向列表中的一个节点,从列表中删除该节点。

    删除列表的某个元素,只知道根据头节点,和待删节点值,遍历搜索到相同值,将其删除。对于给定节点从列表中删除,没有思路。在网上看了讲解,原来这个是列表的基本操作,O(1) 时间即可完成。看了我对列表还不够熟悉。

    1     void deleteNode(ListNode* node) {
    2         
    3         node->val = node->next->val;
    4         node->next = node->next->next;
    5         
    6     }

    题目提到给定的节点,不会是最末尾节点。这样看了这个算法是有缺陷的,因为不能删除最后一个元素。其实不是,只需要在原本的列表最后,插入一个符号代表 NULL ,那么这个算法就对整个列表的完整操作。

    参考资料:

    [LeetCode]Delete Node in a Linked List, 书影 

  • 相关阅读:
    [WC2010]重建计划
    [POJ1741]Tree
    [NOI2008]志愿者招募
    [BZOJ2127]happiness
    「网络流 24 题」太空飞行计划
    [TJOI2015]线性代数
    [HDU2874]Connections between cities
    [POI2007]ZAP-Queries
    [SCOI2010]幸运数字
    POJ 2826 An Easy Problem?!
  • 原文地址:https://www.cnblogs.com/TonyYPZhang/p/5090487.html
Copyright © 2020-2023  润新知