leetcode11.Linked List Cycle II
来源:互联网 发布:java byte类型 编辑:程序博客网 时间:2024/05/22 00:51
问题比之前的那个问题麻烦了点
iven a linked list, return the node where the cycle begins. If there is no cycle, return null
.
Follow up:
Can you solve it without using extra space?
思路:依旧快慢指针,当相遇之后,慢指针退回到头节点处,俩指针通速度前进至相遇
java:
package leetcode9.LinkHasOrNotCycle;class ListNode{int val;ListNode next;ListNode(int x){val=x;next=null;}}public class Solution_II {public ListNode detectCycle(ListNode head){if(head==null){return null;}ListNode fast=head;ListNode slow=head;while(fast.next!=null){fast=fast.next.next;if(fast==null){return null;}slow=slow.next;if(fast==slow){ slow = head; while (fast != slow) { fast = fast.next; slow = slow.next; } return fast; }}return null;}}
证明原理:
设:链表头是X,环的第一个节点是Y,slow和fast第一次的交点是Z。各段的长度分别是a,b,c,如图所示。环的长度是L。slow和fast的速度分别是qs,qf。
第一次相遇时slow走过的距离:a+b,fast走过的距离:a+b+c+b。
因为fast的速度是slow的两倍,所以fast走的距离是slow的两倍,有 2(a+b) = a+b+c+b,可以得到a=c(这个结论很重要!)。
如果圈很小,而a很长,那么b的长度就会是绕圈几周了,但是结果也是一样成立的。
证明来源于:http://blog.csdn.net/kenden23/article/details/13871699
0 0
- leetcode11.Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- spring+ibatis事务配置
- 每日一得--iBatis高级应用
- 商超连锁行业异速联解决方案
- android 基础面试题
- weblogic 修改默认字符编码 乱码问题
- leetcode11.Linked List Cycle II
- Flex DataGrid内容自动换行相关
- MongoDB 数据库M-S主从复制
- Google查询参数含义
- FTP数字代码的意义
- PHP环境搭建 环境搭建
- ViewPager延时加载(懒加载)
- android.intent.action.MAIN 和android.intent.category.LAUNCHER
- linux 安装 MySQLdb for python