LeetCode:Linked List Cycle II

来源:互联网 发布:JavaScript 中的注释 编辑:程序博客网 时间:2024/06/08 15:36

这道题代码难度并不大,主要是在于怎么想两个快慢指针的运动。

假设轨道长是K1,经过m步,慢指针pslow到达轨道的K2位置与pfast相等。所以得到第一个等式K1+K2=m。(1)

此时pfast跑了2m步,即K1+K2+xl=2m。(l指圈长,x指圈数)。

此时把pfast移到head处,步长改为1,经过K1步,刚到到达环开始处,而此时,pslow从K2经过K1步,经过(1)等式,刚好也在环起始处,此时返回pfast就好了。

/** * 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) {        if(head==NULL||head->next==NULL)return NULL;        ListNode* pfast=head;        ListNode* pslow=head;while(pfast!=NULL&&pfast->next!=NULL){pfast=pfast->next->next;pslow=pslow->next;if(pfast==pslow){pfast=head;while(pfast!=pslow){pfast=pfast->next;pslow=pslow->next;} return pfast;}} return NULL;    }};


0 0
原创粉丝点击