LeetCode 142 Linked List Cycle II
来源:互联网 发布:java float 精度 编辑:程序博客网 时间:2024/06/05 14:13
题目描述
Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
Note: Do not modify the linked list.
Follow up:
Can you solve it without using extra space?
分析
LeetCode 141 Linked List Cycle
以下参考:[原]求单链表环的入口结点 Linked List Cycle II
slow指针每次走1步,fast指针每次走2步。如果链表有环,那么两个指针一定会相遇。
设链表头到环入口结点的结点数目是a,环内的结点数目r。假设相遇时,fast指针已经绕环转了n圈,比slow多走了n*r步。假设环的入口结点到相遇结点的结点数目为x。
那么在相遇时,slow走了a+x步,fast走了a+x+n*r步。
由于fast的步调是slow的两倍,所以有a+x = n*r。因而,a = n*r - x
显然,从相遇位置开始,走n*r - x步,一定可以到达环的入口结点;从链表头开始,走a步,也会到达环的入口。并且我们得到了a = n*r - x。所以我们让两个指针,一个从相遇位置出发一个从链表头出发,让他们都单步前进。因为a = n*r - x,所以他们一定会在环的入口相遇。
代码
public static ListNode detectCycle(ListNode head) { if (head == null) { return null; } ListNode slow = head; ListNode fast = head.next; boolean meet = false; int len = 0; // 判断是否有环,并计数 while (fast != null) { if (fast.next == null || fast.next.next == null) { return null; } if (slow == fast) { if (meet) { break; } meet = true; } fast = fast.next.next; slow = slow.next; if (meet) { len++; } } if (meet) { slow = head; fast = head; // fast先走len步 for (int i = 0; i < len; i++) { fast = fast.next; } // slow从起始点出发,fast从len处出发 // 二者相遇的结点,即为入环结点 while (slow != fast) { slow = slow.next; fast = fast.next; } return slow; } return null; }
0 0
- LeetCode.142(141) Linked List Cycle && Linked List Cycle (II)
- LeetCode 142 Linked List Cycle II
- LeetCode 142 Linked List Cycle II
- LeetCode: Linked List Cycle II [142]
- [leetcode 142]Linked List Cycle II
- Leetcode NO.142 Linked List Cycle II
- [leetcode]142 Linked List Cycle II
- [LeetCode 142]Linked List Cycle II
- leetcode || 142、Linked List Cycle II
- 【leetcode】【单链表】【142】Linked List Cycle II
- [Leetcode 142] Linked List Cycle II
- [leetcode-142]Linked List Cycle II(c)
- leetcode 142: Linked List Cycle II
- leetCode #142 Linked List Cycle II
- Leetcode #142 Linked List Cycle II
- 142 Linked List Cycle II [Leetcode]
- 【LEETCODE】142-Linked List Cycle II
- LeetCode 142 Linked List Cycle II
- Starterware On Beaglebone Black(一) 环境搭建
- 《算法竞赛入门经典2ndEdition 》习题3-3 数数字(Digit Counting, Uva1225)
- 第十四周--是否二叉排序树?
- springMVC第一课:配置
- SpringMVC_@RequestMapping&Controller的返回值
- LeetCode 142 Linked List Cycle II
- iOS中的模糊视图效果
- Scala :foldLeft foldRight min max
- web后台分层详解
- 关于单链表
- 进制转换
- cocos2d js显示远程下载的图片资源
- Java多线程-synchronized关键字
- 截屏方式