【Leetcode】【Medium】Linked List Cycle II

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

 

解题:

寻找单链表中环的入口,如果不存在环则返回null。

假设单链表有环,先利用判断单链表是否有环(Linked List Cycle)的方法,找到快慢指针的交点。

假设环的入口在第K个结点处,那么此时快慢指针的交点,距离环入口,还差k个距离。

快慢指针相交后,在链表头位置同时启动另一个指针target,和慢指针once一样每次只移动一步,那么两者同时移动K步,就会相交于入口处。

 

 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 || head->next == NULL) 
13             return NULL;
14         ListNode* once = head;
15         ListNode* twice = head;
16         ListNode* target = head;
17         
18         while (twice->next && twice->next->next) {
19             once = once->next;
20             twice = twice->next->next;
21             if (once == twice) {
22                 while (target != once) {
23                     target = target->next;
24                     once = once->next;
25                 }
26                 return target;
27             }
28         }
29         
30         return NULL;
31     }
32 };

 

posted @ 2015-06-21 04:01  胡潇  阅读(191)  评论(0编辑  收藏  举报