链表是否有环

1-a (true or false)
[https://leetcode-cn.com/problems/linked-list-cycle/](LeetCode 141)

//方法1、利用STL中set

class Solution {
public:
bool hasCycle(ListNode head) {
set<ListNode
>s;
while(head){
if(s.find(head)==s.end()){
s.insert(head);
head=head->next;
}
else
return true;
}
return NULL;
}
};

//方法2、快慢指针在环上相遇

class Solution {
public:
bool hasCycle(ListNode head) {
ListNode
pFast=head;
ListNode* pSlow=head;

do{
if(pFast){
pSlow=pSlow->next;
pFast=pFast->next;
}
if(pFast)
pFast=pFast->next;
if(!pFast)
return false;
}while(pFast!=pSlow);
if(pFast){
return true;
}
else
return false;
}
};

1-b (return Pos)
[https://leetcode-cn.com/problems/linked-list-cycle-ii/](LeetCode 142)

//方法1、利用set

class Solution {
public:
ListNode *detectCycle(ListNode head) {
set<ListNode
>s;
while(head){
if(s.find(head)==s.end()){
s.insert(head);
head=head->next;
}
else
return head;
}
return NULL;
}
};

//方法2、快慢指针
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
if(head == NULL||head->next == NULL)
return nullptr;

ListNode* pFast=head;
ListNode* pSlow=head;

ListNode* meet=NULL;
ListNode* ifNULL=head;

do{
if(pFast!=NULL){
pFast=pFast->next;
pSlow=pSlow->next;
}
if(pFast!=NULL)
pFast=pFast->next;
if(pFastNULL){
return NULL;
}
}while(pFast!=pSlow);//when(pFast
pSlow) break;

while(pSlow!=head&&pSlow){//从相遇位置走,从开始节点走,步速一致,相遇即为环入口节点
pSlow=pSlow->next;
head=head->next;
}
meet=pSlow;
return meet;
}
};

posted @ 2020-11-05 12:56  Colin_Code  阅读(60)  评论(0)    收藏  举报