您的位置:首页 > 其它

linked-list-cycle-ii

2017-07-03 16:11 295 查看
Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

Follow up:

Can you solve it without using extra space?

剑指offer里也有同样的题,分为三步找到环形链表的入口结点,这里就只记录这次自己写的代码,具体的思路分析见链表中环的入口结点

代码:

/**
* 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 *meetingnode = meetingcycle(head);
if(meetingnode==NULL)
return NULL;

//计算环内节点个数
int count = 1;
ListNode *cur = meetingnode;
while(cur!=NULL){
cur = cur->next;
if(cur==meetingnode)
break;
count++;//这里要注意break和count++的顺序问题
}

//寻找入口点
ListNode *slow = head;
ListNode *fast = head;
for(int i = 0;i < count;++i){
fast = fast->next;
}
while(slow!=fast){
slow = slow->next;
fast = fast->next;
}
return slow;
}

//找到一个环内节点
ListNode *meetingcycle(ListNode *head){
if(head==NULL || head->next==NULL)
return NULL;
ListNode *slow = head;
ListNode *fast = head->next;
while(slow!=NULL && fast!=NULL){
if(slow==fast)
return slow;
slow = slow->next;
fast = fast->next;
if(fast!=NULL)
fast = fast->next;
}
return NULL;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: