[leetcode] #141 Linked List Cycle
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
用O(1)空间,判断单链表是否存在环
解题思路:
1、fast指针走两步, low指针走一步
2、循环后,若有环则存在fast指针追上low指针那一刻。
至于为何走两步,而不走3步,4步
fast指针每次都比low指针多走一步,若有环,假设一开始差距为n。则每次都缩减一步,当差距为0时,自然两者重合了,走3步,4步, 若n不能整除(3-1)或(4-1)需更多圈才能重合。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool hasCycle(ListNode *head) {
ListNode *low = head;
ListNode *fast = head;
while (low && fast && fast->next) {
low = low->next;
fast = fast->next->next;
if (low == fast) {
return true;
}
}
return false;
}
};