leetcode-141. 环形链表
作者:互联网
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;
}
标签:head,slow,ListNode,141,fast,next,链表,return,leetcode 来源: https://blog.csdn.net/qq_42250642/article/details/120969677