第一种解法:hash表
//hash表形式,最高只能到第二梯队
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
const static int x=[]{
std::ios::sync_with_stdio(false);
std::cin.tie(NULL);
return NULL;
}();
//这里有两个坑,第一个是是否有循环,第二个是循环在哪里
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
if(head == NULL) return NULL;
map<ListNode*,int> m;
ListNode *p=head;
while(p){
if(m.count(p)!=0){
return p;
}else{
m[p]=1;
}
p=p->next;
}
return p;
}
};
第二种解法:
两个指针p1,p2,p1每次移动一个节点,p2每次移动两个节点,两个指针相遇的时候表明有循环,否则没有,要特别注意边界。
寻找循环的开始节点是在判断有循环后,p1指向head,然后p1和p2同时直移动一个节点,两个指针碰面就是循环开始的位置了。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
const static int x=[]{
std::ios::sync_with_stdio(false);
std::cin.tie(NULL);
return NULL;
}();
//这里有两个坑,第一个是是否有循环,第二个是循环在哪里
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
ListNode *p1,*p2;
p1=p2=head;
while(p2 && p2->next){
p1=p1->next;
p2=p2->next->next;
if(p1 == p2) break;
}
if(p2==NULL || (p2->next==NULL)) return NULL;
p1=head;
while(p1!=p2){
p1=p1->next;
p2=p2->next;
}
return p1;
}
};