File tree Expand file tree Collapse file tree
solutions/141. Linked List Cycle Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ /**
2+ * 1、Floyd判圈法(之前一直叫双指针跑圈法来着)
3+ *
4+ *
5+ */
6+ /**
7+ * Definition for singly-linked list.
8+ * class ListNode {
9+ * int val;
10+ * ListNode next;
11+ * ListNode(int x) {
12+ * val = x;
13+ * next = null;
14+ * }
15+ * }
16+ */
17+ public class Solution {
18+ public boolean hasCycle (ListNode head ) {
19+ if (head == null || head .next == null )
20+ return false ;
21+
22+ ListNode slow = head ;
23+ ListNode fast = head ;
24+ do {
25+ if (fast == null || fast .next == null ) return false ;
26+
27+ slow = slow .next ;
28+ fast = fast .next .next ;
29+ }while (slow != fast );
30+ return true ;
31+ }
32+ }
Original file line number Diff line number Diff line change 1+ /**
2+ * 在Linded List Cycle I的基础上再求出环的起始节点
3+ *
4+ *
5+ */
6+ /**
7+ * Definition for singly-linked list.
8+ * class ListNode {
9+ * int val;
10+ * ListNode next;
11+ * ListNode(int x) {
12+ * val = x;
13+ * next = null;
14+ * }
15+ * }
16+ */
17+ public class Solution {
18+ public ListNode detectCycle (ListNode head ) {
19+ if (head == null || head .next == null )
20+ return null ;
21+
22+ ListNode slow = head ;
23+ ListNode fast = head ;
24+ do {
25+ if (fast == null || fast .next == null ) return null ;
26+
27+ slow = slow .next ;
28+ fast = fast .next .next ;
29+ }while (slow != fast );
30+
31+ ListNode start = head ;
32+ while (slow != start ){
33+ slow = slow .next ;
34+ start = start .next ;
35+ }
36+ return start ;
37+ }
38+ }
Original file line number Diff line number Diff line change 1+ ###参考
2+ 1 . [ wiki Floyd] ( https://en.wikipedia.org/wiki/Cycle_detection#Tortoise_and_hare )
3+
4+ ###判断链表有环的相关问题:
5+ 1、链表是否有环
6+ > 双指针,一个slow一次一步,一个fast一次两步,如果相遇,则有环;如果fast指向null,则无环。
7+
8+ [ Leetcode 问题:141. Linked List Cycle] ( https://leetcode.com/problems/linked-list-cycle/ )
9+
10+ 2、如果有环,求环的长度
11+ > 接上,双指针,第一次相遇后开始计数,再次相遇,则为环长
12+
13+ 3、求环的起点
14+ > 设初始起点到环的起点距离为** m** ,环的长度为** n** ,第一次相遇时候距离环的起点为** k**
15+ 第一次相遇slow跑的节点数 i = m + a * n + k (1)
16+ 第一次相遇fast跑的节点数 2i = m + b * n + k (2)
17+ (2) - (1): i = (b - a) * n
18+ 可知慢节点跑的距离为环长的整数倍,即 m + k = c * n,也就是:
19+ 如重新设置一个新的指针指向起始节点new,开始计数,当new与slow相遇时候,这个点就是环的起点
20+
21+ [ Leetcode 问题:142: Linked List Cycle II] ( https://leetcode.com/problems/linked-list-cycle-ii/ )
You can’t perform that action at this time.
0 commit comments