Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
解题思路
使用快慢两个指针,如果快的指针赶上了慢的,则说明存在回路。
实现代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
//Runtime:18 ms
class Solution {
public:
bool hasCycle(ListNode *head) {
if (head == NULL)
{
return false;
}
ListNode *slow = head;
ListNode *fast = head;
while (fast->next && fast->next->next)
{
slow = slow->next;
fast = fast->next->next;
if (fast == slow)
{
return true;
}
}
return false;
}
};