题目
思路
- 定义快、慢两个指针,遍历链表;
- 如果链表中不存在环,快指针会先到达尾部,返回false;
- 如果链表中最终未发现快指针与慢指针不相同,返回true。
代码块
/**
* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public bool HasCycle(ListNode head) {
if (head == null || head.next == null)
{
return false;
}
ListNode slow = head;
ListNode fast = head.next;
while (slow != fast)
{
if (fast == null || fast.next == null)
{
return false;
}
slow = slow.next;
fast= fast.next.next;
}
return true;
}
}
运行结果
来源:CSDN
作者:裸奔的海参
链接:https://blog.csdn.net/luobendehaishen/article/details/104820995