Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
Subscribe to see which companies asked this question
這裏要注意 邊界條件由快那個指針確定 不用考慮慢那個 若只考慮快那個一次走兩步的情況 那麼 一次走兩步若next爲空 next->next則無法訪問
/**
* 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) {
//設置兩個指針,一個走兩步一個走一步 有環必然會存在相等的時候
if(head == NULL){
return false;
}
if(head->next == head){
return true;
}
ListNode*t1 = head;
ListNode*t2 = head;
//這裏要注意 邊界條件由快那個指針確定 不用考慮慢那個 若只考慮快那個一次走兩步的情況 那麼 一次走兩步若next爲空 next->next則無法訪問
while(t2->next!=NULL&&t2->next->next!=NULL){
t1 = t1->next;
t2 = t2->next->next;
if(t1 == t2){
return true;
}
}
return false;
}
};