您的位置:首页 > 其它

Linked List Cycle II 求单链表环的入口

2015-05-20 20:54 176 查看


Linked List Cycle II

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?

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
 
 /*
 假设ptr1需要m步第一次走到环的开始节点,那么ptr2应该走到了环的第m个位置(注意:这里是指环里的位置,ptr1在0处,ptr2在m处)。ptr2每次都比ptr1多走一步且它们都在环内,所以需要n-m步(n是环的大小),才能追上ptr1,达到重合。这个重合位置是[2*(n-m)+m-x*n]%n=n-m,这样我们就可以知道,重合的位置距离环开始节点有m步,head距离环开始节点也是m步。
 */
class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
        
        if(head==NULL)
            return NULL;
        ListNode *slow,*fast;
        slow=head;
        fast=head;
        
        int f=0;
        while(fast!=NULL&&fast->next!=NULL)
        {
            fast=fast->next->next;
            slow=slow->next;
            if(slow==fast)
            {
                f=1;
                break;
            }
        }
        
        if(!f)
            return NULL;
        slow=head;
        while(slow!=fast)
        {
            slow=slow->next;
            fast=fast->next;
        }
        
        return slow;
    }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: