Every day a leetcode
题目来源:141. 环形链表
解法1:快慢指针
详情请参考Leetcode面试题 02.08. 环路检测中的解法。
代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
bool hasCycle(struct ListNode *head) {
if(head == NULL || head->next == NULL) return false;
struct ListNode *slow=head;
struct ListNode *fast=head;
while(fast && fast->next)
{
slow=slow->next;
fast=fast->next->next;
if(slow == fast) break;
}
if(slow!=fast) return false;
else return true;
}
结果: