首页 > 其他 > 详细

Linked List Cycle II

时间:2014-04-07 18:45:01      阅读:507      评论:0      收藏:0      [点我收藏+]

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?

bubuko.com,布布扣
 1 class Solution {
 2 public:
 3     bool isCycle(ListNode* head) {
 4         if (!head) {
 5             return false;
 6         }
 7         ListNode* slow = head;
 8         ListNode* fast = head;
 9         while (slow && fast) {
10             slow = slow->next;
11             if (!fast->next) return false;
12             fast = fast->next->next;
13             if (fast == slow) {
14                 return true;
15             }
16         }
17         return false;
18     }
19     
20     ListNode *detectCycle(ListNode *head) {
21         if (!isCycle(head)) return NULL;
22         ListNode* dummy = new ListNode(0);
23         dummy->next = head;
24         ListNode* slow = dummy;
25         ListNode* fast = dummy;
26         while (slow && fast) {
27             slow = slow->next;
28             fast = fast->next->next;
29             if (slow == fast) {
30                 break;
31             }
32         }
33         
34         slow = dummy;
35         while(slow != fast) {
36             slow = slow->next;
37             fast = fast->next;
38         }
39         return slow;
40     }
41 };
bubuko.com,布布扣

 

Linked List Cycle II,布布扣,bubuko.com

Linked List Cycle II

原文:http://www.cnblogs.com/zhengjiankang/p/3646440.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!