首页 > 其他 > 详细

[LeetCode] 237. Delete Node in a Linked List 解题思路

时间:2015-12-31 01:39:07      阅读:323      评论:0      收藏:0      [点我收藏+]

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] 237. Delete Node in a Linked List 解题思路

原文:http://www.cnblogs.com/TonyYPZhang/p/5090487.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!