环形链表II 142 使用快慢指针(C++实现)

 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         ListNode* slow=head;
13         ListNode* fast=head;
14         ListNode* meet=NULL;
15         
16         while(fast)
17         {
18             slow=slow->next;
19             fast=fast->next;
20             if(!fast)
21             return NULL;
22             fast=fast->next;
23             if(slow==fast)
24                 meet=fast;
25             if(meet==head)
26                 return meet;
27             else if(meet)
28             {
29             meet=meet->next;
30             head=head->next; 
31             }
32         }
33         return NULL;
34     }
35 };

猜你喜欢

转载自www.cnblogs.com/SuzanneHuang/p/10644367.html