题目:
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) {}
* };
*/
class Solution {
public:
//141. Linked List Cycle
//快慢两个指针,若存在环,那么慢指针会赶上快指针
bool hasCycle(ListNode *head) {
if(head == NULL) return false;
ListNode* runner = head;
ListNode* walker = head;
while(runner->next!=NULL && runner->next->next!=NULL){
walker = walker->next;
runner = runner->next->next;
if(walker == runner){
return true;
}
}
return false;
}
};