問題描述
給定一個鏈表,判斷鏈表中是否有環。
爲了表示給定鏈表中的環,我們使用整數 pos 來表示鏈表尾連接到鏈表中的位置(索引從 0 開始)。 如果 pos 是 -1,則在該鏈表中沒有環。
示例 1:
輸入:head = [3,2,0,-4], pos = 1
輸出:true
解釋:鏈表中有一個環,其尾部連接到第二個節點。
解題報告
快慢指針法判斷是否有環。設置快慢指針,如果快慢指針能夠相遇,必定是有環的。
實現代碼
/**
* 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 *slow=head,*fast=head;
while(fast!=NULL&&fast->next!=NULL&&fast->next->next!=NULL){
fast=fast->next->next;
slow=slow->next;
if(slow==fast){
return true;
}
}
return false;
}
};