码迷,mamicode.com
首页 > 其他好文 > 详细

linked-list-cycle-ii——链表,找出开始循环节点

时间:2017-06-08 00:15:31      阅读:215      评论:0      收藏:0      [点我收藏+]

标签:public   without   solution   指针   blog   init   ini   null   break   

Given a linked list, return the node where the cycle begins. If there is no cycle, returnnull.

Follow up:
Can you solve it without using extra space?

 

快慢指针找重合判断是否循环、而后fast从头开始+1,slow继续前进直到重合

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     ListNode *detectCycle(ListNode *head) {
12         if(head==NULL)
13             return NULL;
14         ListNode *fast=head,*slow=head;
15         ListNode *res=NULL;
16         while(fast!=NULL&&fast->next!=NULL){
17             fast=fast->next->next;
18             slow=slow->next;
19             if(fast==slow){
20                 res=fast;
21                 break;
22             }
23         }
24         if(res==NULL)
25             return res;
26         
27         fast=head;
28         while(fast!=res){
29             fast=fast->next;
30             res=res->next;
31         }
32         return res;
33     }
34 };

 

linked-list-cycle-ii——链表,找出开始循环节点

标签:public   without   solution   指针   blog   init   ini   null   break   

原文地址:http://www.cnblogs.com/zl1991/p/6959572.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!