leetcode-141. 环形链表
题目:
代码:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct ListNode{
int val;
ListNode *next;
};
//方法一:遍历
bool hasCycle(ListNode *head) {
vector<ListNode*> v;
while(head){
if(std::find(v.begin(),v.end(),head)!=v.end()){
return true;
}
v.push_back(head);
head=head->next;
}
return false;
}
//方法二:Floyd判圈算法
bool hasCycle1(ListNode *head) {
if(!head || !head->next){
return false;
}
ListNode *slow=head;
ListNode *fast=head->next;
while(slow!=fast){
if(!fast || !fast->next){
return false;
}
slow=slow->next;
fast=fast->next->next;
}
return true;
}
int main(){
ListNode *head;
bool res;
res=hasCycle(head);
cout<<res;
return 0;
}