题目描述:
思路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;
}
};