leetcode------Linked List Cycle

标题:

Linked List Cycle

通过率: 36%
难度 中等

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

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

拿到题后我以为很简单,题目中给出不用额外的空间我不知道什么意思,我单纯的认为判断是否有环,如果是我认为单纯的一个环那么只用用一个节点去记录头结点,然后开始循环遍历,直到再次回到头部。如果能回到便是一个循环链。提交代码后发现提示为:             

Last executed input: {3,2,0,-4}, tail connects to node index 1

突然就蒙圈了!怎么会出现这种循环链表呢,我都惊呆了。然后我就只能开始查资料了。我用个图来展示这个问题的

 

对于这种链表我都醉了。到底要如何去判断有没有环环,我只能又去查找了。

经过查找我发现网上最为流行且效率最高的便是两个指针开始遍历且速度不一样,具体怎么处理的我下面进行详细解释:

1、设定两个指针:A、B,且开始时都指向头部

2、A的遍历方式为:A=A.next,即一步一步走。B的遍历方式为:B=B.next.next,即一次走两步。

有了以上两个方式,我们可以想如果有环那么B一定是可以追上A的。如果没有环那么B将最先走到最后。

有了上面的解释我相信已经很明确了。下面直接上代码来进行具体阐述:

 1 public class Solution {
 2     public boolean hasCycle(ListNode head) {
 3         if(head==null) return false;
 4         if(head.next==null) return false;
 5         if(head.next.next==null) return false;
 6         
 7         ListNode slow=head;
 8         ListNode fast=head;
 9         
10         while(fast!=null && fast.next!=null){
11             slow=slow.next;
12             fast=fast.next.next;
13             if(fast==slow){
14                 return true;
15             }
16         }
17         return false;
18         
19     }
20 }
原文地址:https://www.cnblogs.com/pkuYang/p/4157738.html