题目
题目链接:
https://www.nowcoder.com/practice/650474f313294468a4ded3ce0f7898b9
思路
如果有环,慢指针slow每一次走一步,快指针每次走2步,如果两个指针相遇,那么就有环
这和操场跑步一个道理,如果slow这个人每个时间单位跑一米,fast这个每个时间单位跑2米,
最终2个人会在某一时刻相遇的。但是如果不是操场,就不会相遇
参考答案
import java.util.*;
/**
* 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) {
if (head == null) return false;
ListNode slow = head; //慢指针
ListNode fast = head; //快指针
while (fast.next != null &&
fast.next.next != null) { //这个while条件要记住
slow = slow.next;
fast = fast.next.next;
if (slow == fast) return true;
}
return false;
}
}