Linked List Cycle

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

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

描述

判断一个链表是否是环,要求不能使用额外空间辅助

分析

设计一个快指针和一个慢指针,快指针每次走两步,慢指针每次走一步,若两个指针相遇,且指针不为空,则存在环

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/

public class Solution {
public boolean hasCycle(ListNode head) {

ListNode fast, slow;
fast = slow = head;

while (fast != null && fast.next != null) {

fast = fast.next.next;
slow = slow.next;

if (fast == slow) {
return true;
}
}

return false;
}
}