LeetCode编程练习

来源:互联网 发布:网络玄幻小说大纲模板 编辑:程序博客网 时间:2024/06/16 23:16

题目:

    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 is1 -> 2 -> 3 -> 4 and you are given the third node with value3, the linked list should become1 -> 2 -> 4after calling your function.

    编写一个函数来删除一个单独的链表中的节点(出来尾部),只允许访问该节点。


思路:

    直接判断与给定值是否相同,若相同将下一个指针赋值个当前。但运行错误。


    但解决方案中给出的建议,从链表中删除节点的通常方法是修改其前面的节点的下一个指针,然后指向它之后的指针,而我的思路并没有修改,而是直接判断是否相同。由于没有访问要删除的节点前的节点,因此不能以任何方式修改该节点的下一个指针。只要替换想要删除的节点的值,然后在它后面的节点上删除它,然后删除它之后的节点。也就是说,先将需要删除的节点的指针替换成下一个指针,然后在把它删除。