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

来源:互联网 发布:科蓝软件 编辑:程序博客网 时间:2024/06/06 16:25

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;    }};

0 0