题目描述:

LeetCode_142. Linked List Cycle II_快慢指针


思路1:建立一个vector用来存放已经访问过的链表节点,如果没有访问过,则添加到vector中并继续向后访问,否则则是cycle的入口节点。

/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
if(head==NULL)
return NULL;
vector<ListNode*> res;
ListNode* p=head;
while(p){
vector<ListNode*>::iterator it=find(res.begin(),res.end(),p);
if(it==res.end()){
res.push_back(p);
p=p->next;
}
else
return p;
}
return NULL;
}
};

思路2:采用快慢指针思路同​​linked list cycle​​,这道题需要知道cycle共有N个节点,然后让fast指针提前走N个节点,然后fast指针和slow指针一起向前一个节点一个节点移动,当相遇的时候,就是cycle的入口节点。

/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
ListNode* meetNode=meetingNode(head);
if(meetNode==NULL)
return NULL;
ListNode* p=meetNode->next;
int count=1;
while(p!=meetNode){
count++;
p=p->next;
}
ListNode *fast=head;
ListNode *slow=head;
while(count--){
fast=fast->next;
}
while(slow!=fast){
slow=slow->next;
fast=fast->next;
}
return slow;
}
//查找环中节点个数
ListNode *meetingNode(ListNode* pNode){
if(pNode==NULL)
return NULL;
ListNode* slow=pNode;
ListNode* fast=slow->next;
if(fast==NULL)
return NULL;
while(fast){
if(fast==slow)
return fast;
slow=slow->next;
fast=fast->next;
if(fast)
fast=fast->next;
}
return NULL;
}
};