Lintcode372 Delete Node in the Middle of Singly Linked List solution 题解
【题目描述】
Implement an algorithm to delete a node in the middle of a singly linked list, given only access to that node.
给定一个单链表中的一个等待被删除的节点(非表头或表尾)。请在在O(1)时间复杂度删除该链表节点。
【题目链接】
www.lintcode.com/en/problem/delete-node-in-the-middle-of-singly-linked-list/
【题目解析】
一般单链表删除某个节点,需要知道删除节点的前一个节点,则需要O(n)的遍历时间,显然常规思路是不行的。
在仔细看题目,换一种思路,既然不能在O(1)得到删除节点的前一个元素,但我们可以轻松得到后一个元素,这样,我们何不把后一个元素赋值给待删除节点,这样也就相当于是删除了当前元素。可见,该方法可行。
但如果待删除节点为最后一个节点,则不能按照以上思路。没有办法,只能按照常规方法遍历,时间复杂度为O(n),是不是不符合题目要求呢?可能很多人在这就会怀疑自己的思考,从而放弃这种思路,最后可能放弃这道题,这就是这道面试题有意思的地方,虽看简单,但是考察了大家的分析判断能力,是否拥有强大的心理,充分自信。
其实我们分析一下,仍然是满足题目要求的,如果删除节点为前面的n-1个节点,则时间复杂度为O(1),只有删除节点为最后一个时,时间复杂度才为O(n),所以平均的时间复杂度为:(O(1) * (n-1) + O(n))/n = O(1);仍然为O(1).
【参考答案】
www.jiuzhang.com/solutions/delete-node-in-the-middle-of-singly-linked-list/
转载于:https://www.cnblogs.com/qiangqingci/p/8732433.html
Lintcode372 Delete Node in the Middle of Singly Linked List solution 题解相关推荐
- [LintCode] Delete Node in the Middle of Singly Linked List 在单链表的中间删除节点
Implement an algorithm to delete a node in the middle of a singly linked list, given only access to ...
- LintCode Delete Node in the Middle of Singly Linked List 在O(1)时间复杂度删除链表节点
中文描述: 给定一个单链表中的表头和一个等待被删除的节点(非表头或表尾).请在在O(1)时间复杂度删除该链表节点.并在删除该节点后,返回表头. 样例 给定 1->2->3->4,和节 ...
- lintcode-easy-Delete Node in the Middle of Singly Linked List
Implement an algorithm to delete a node in the middle of a singly linked list, given only access to ...
- 876. Middle of the Linked List - LeetCode
为什么80%的码农都做不了架构师?>>> Question 876. Middle of the Linked List Solution 题目大意:求链表的中间节点 思路:构 ...
- 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 t ...
- 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 t ...
- Leet Code OJ 237. Delete Node in a Linked List [Difficulty: Easy]
题目: Write a function to delete a node (except the tail) in a singly linked list, given only access t ...
- 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 t ...
- C#LeetCode刷题之#237-删除链表中的节点(Delete Node in a Linked List)
问题 该文章的最新版本已迁移至个人博客[比特飞],单击链接 https://www.byteflying.com/archives/3832 访问. 请编写一个函数,使其可以删除某个链表中给定的(非末 ...
最新文章
- 负载均衡(SLB)使用最佳实践
- 基于中间代码的优化中,循环的查找算法有哪些?循环优化的方法有哪些?举例说明。
- 利用eigen库简单实现矩阵功能
- iOS sql的简单封装
- java复合数据类型_复合数据类型
- cannot open file mfc42u.lib的问题解决
- 读写自旋锁详解,第 3 部分(来自IBM)
- JavaWeb:前端开发基础
- Fedora17下安装OpenCV2.3.1[转]
- BZOJ 4802 欧拉函数(Pollard_Rho)
- Linux 软件安装位置选择指南
- win7原版系统安装及基本设置
- ps动作储存覆盖原文件的原因
- elasticsearch中忽略大小写模糊搜索实现
- 免费易混实词辨析456组(1)
- 疫苗预约系统,疫苗预约管理系统,疫苗预约小程序系统设计与实现
- matlab取矩阵元素的模,matlab – 提取矩阵元素
- Android 后台启动startService()相关问题的解决
- BZOJ2277 [Poi2011]Strongbox 【数论】
- Vitis-AI运行Emulation-HW神坑