现在的位置: 首页 > 综合 > 正文

leetcode:linked_list_cycle_II

2018年04月08日 ⁄ 综合 ⁄ 共 772字 ⁄ 字号 评论关闭

一、     题目

        给定一个链表,如果链表中有环则返回环的开始节点,否则返回NULL。要求不用额外的空间完成。

二、     分析

       在I中,我们判断环的存在,即用slow和fast两个指针,设定步长fast=2;slow=1;如果两个指针可以相遇则环存在,此时如果二者相遇我们只需将slow=head;同时设置两者步长都为1,则两者再次相遇的节点即为环的开始节点。

推导过程:(图烂勿吐)

                

          当两者第一次相遇时,

          slow走过S1=x + y;

          fast走过S2=x + y + z + y,

         又知S2=2 * S1;

         所以,2 *(x+y) = x + y + z + y;

         故,x = z;

 

 

<span style="font-size:18px;">/**
 * 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 *slow = head;
	   ListNode *fast = head;
	   
	   while(fast!=NULL&&fast->next != NULL) {
	   	slow = slow->next;
	   	fast = fast->next->next;
	   	if(slow==fast) break; 
	   }  
	   if(fast==NULL||fast->next==NULL) {
	   	return NULL;
	   }
	   slow=head;
	   while(slow!=fast) {
	   	slow = slow->next;
	   	fast = fast->next;
	   }
	   return fast;
    }
};</span>

抱歉!评论已关闭.