題目描述:
思路1:申請一個vector用來存放已經訪問過的節點,在遍歷鏈表的過程中,如果發現已經訪問過該節點,則說明鏈表存在環,否則不存在
/**
* 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;
vector<ListNode*> visited;
ListNode* p=head;
while(p){
vector<ListNode*>::iterator it=find(visited.begin(),visited.end(),p);
if(it==visited.end()){
visited.push_back(p);
p=p->next;
}else{
return true;
}
}
return false;
}
};
思路2:設置快慢指針,fast和slow,fast指針每次走兩個節點,slow指針每次走一個節點。fast一開始就在slow前面,如果fast==slow了,說明存在環。
/**
* 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;
ListNode *fast,*slow;
fast=slow=head;
if(fast->next==NULL||fast->next->next==NULL)//一個節點或兩個節點
return false;
while(fast){
slow=slow->next;
fast=fast->next;
if(fast!=NULL)//在移動兩次的時候必須要判斷第一次移動後是否是NULL
fast=fast->next;
if(fast==slow)
return true;
}
return false;
}
};