[LeetCode]LinkedListCycle 和LinkedListCycle2

Posted zlz099

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode]LinkedListCycle 和LinkedListCycle2相关的知识,希望对你有一定的参考价值。

题目1:

Given a linked list, determine if it has a cycle in it.

Follow up:
Can you solve it without using extra space?

题目2:

Given a linked list, return the node where the cycle begins. If there is no cycle, returnnull.

Follow up:
Can you solve it without using extra space?

思路1:快慢指针,查找是否存在环。

思路2:

一个链表中包含环,请找出该链表的环的入口结点。

判断是否包含环:快慢指针,fast的速度是low的2倍。如果存在fast=low,那就存在环。
 找环的入口,则有数学公式:
 设起点到环入口的距离为a,入口到相遇的距离为b,相遇后到入口的距离为c 则因为fast是low的2倍,
 Sfast = a+b+c+b
 Slow = a+b
 Sfast = 2Slow a+b+c+b = 2(a+b) -> c = a
 得到c=a这个结论就好办了,在第一次相遇之后,让fast回到起点,fast和low都每次移动一个单位,
 low走过c距离,fast走过a距离,是一样的,刚好回到环的入口点。

 1 public class LinkedListCycle {
 2     public boolean hasCycle(ListNode head) {
 3         if(head == null) return false;
 4         ListNode fast = head;
 5         ListNode slow = head;
 6         while(fast.next!=null&&fast.next.next!=null){
 7             fast = fast.next.next;
 8             slow = slow.next;
 9             if(fast == slow){
10                 return true;
11             }
12         }
13         return false;
14         
15     }
16 }
 1 public class LinkedListCycle2 {
 2     public ListNode detectCycle(ListNode head) {
 3         
 4         if(head == null || head.next == null){
 5             return null;
 6                 
 7         }
 8         ListNode fast = head;
 9         ListNode low = head;
10         while(fast.next!=null){
11             fast = fast.next.next;
12             low = low.next;
13             
14             if(fast == low){
15                 fast = head;
16                 while(fast!=low){
17                     fast = fast.next;
18                     low = low.next;
19                 }
20                 if(fast == low){
21                     return low;
22                 }
23             }
24         }
25         return null;
26     
27     }
28 }

 










以上是关于[LeetCode]LinkedListCycle 和LinkedListCycle2的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode Linked List Cycle II

LeetCode 141

leetcode-141. Linked List Cycle

leetcode.142 LinkedList Cycle II

LeetCode-day05

[leetcode] Linked List Cycle