public boolean hasCycle(ListNode head) {
if (head == null)
return false;
//快慢两个指针
ListNode slow = head;
ListNode fast = head;
while (fast != null && fast.next != null) {
//慢指针每次走一步
slow = slow.next;
//快指针每次走两步
fast = fast.next.next;
//如果相遇,说明有环,直接返回true
if (slow == fast)
return true;
}
//否则就是没环
return false;
}
老师给的代码:
#include <stdio.h>
static int find_loop (int a[], int n)
{
int ptr1, ptr2; //slow & fast
ptr1 = a[0]; //once a step
ptr2 = a[0]; ptr2 = a[ptr2]; //two steps
while (ptr1 != ptr2)
{
if (ptr1 < 0 || ptr1 >= n || ptr2 < 0 || ptr2 >= n)
return (-1);
ptr1 = a[ptr1];
ptr2 = a[a[ptr2]];
}
ptr1 = 0; //back to header
while (ptr1 != ptr2)
{
ptr1 = a[ptr1]; //same pace
ptr2 = a[ptr2];
}
return (ptr1);
}
static int aa[11] = {1,2,3,4,5,6,7,8,9,2,3};
int main ()
{
printf ("loop starts at %d
", find_loop (aa, 11));
return (0);
}
由于题目描述的是按顺序索引的单链表,导致我没理清楚意思,而且题目给的样例也有些问题,所以,就照网上常规的情况来写了。上面的 Java 代码来自 LeetCode,C 代码来自课堂。结合代码,题目的意思大概是理解了。