LeetCode141-环形链表

题目链接

英文链接:https://leetcode.com/problems/linked-list-cycle/

中文链接:https://leetcode-cn.com/problems/linked-list-cycle/

题目详述

给定一个链表,判断链表中是否有环。

进阶:
你能否不使用额外空间解决此题?

题目详解

  • 使用双指针,一个快指针,一个慢指针。
  • 快指针每次走两步,慢指针每次走一步。如果有环,快指针一定会追上慢指针。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class LeetCode_00141 {

public boolean hasCycle(ListNode head) {
ListNode fast = head;
ListNode slow = head;
while (fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
if (fast == slow) {
return true;
}
}
return false;
}
}