[LeetCode]Linked List Cycle II

来源:互联网 发布:河北省软件企业 编辑:程序博客网 时间:2024/06/06 06:54

题目链接:Linked List Cycle II

题目内容:

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

Note: Do not modify the linked list.

Follow up:
Can you solve it without using extra space?

题目解法:

题目要求判断链表中是否有环,如果有,要返回环的起始结点,否则返回空。
这道题的关键有二,一是环的判定,二是找到环的起点。幸运的是,这两个问题都可以用双指针法解决。

  • 双指针法
    双指针法是指使用两个指针slow、fast,开始都指向头结点,接着slow每次移动一步,fast每次移动两步。

  • 判断环
    因为fast每次都比slow多走一步,当两者都进入环路时,设二者顺时针相距k,那么每次fast都比slow多走一步,一定可以在有限步数内弥补这段距离,从而相遇,因此当fast==slow时我们可以知道有环存在。

  • 找起点
    路径示意图

    我们设slow和fast在Z点相遇,那么当相遇时,slow走过的距离为a+b,fast走过的距离为a+b+c+b,又因为fast走过的距离是slow的2倍,因此2(a+b)=a+2b+c,也就是a=c,因此在相遇时,我们把slow重新指向起点X,然后每次fast和slow都只走一步,因为a=c,当两者相遇时恰好在Y点,也就是环的起点。

  • 代码

    /*** 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;    ListNode *fast;    if(head == NULL || head->next == NULL || head->next->next == NULL) return NULL;    slow = head->next;    fast = head->next->next;    while(1){        if(slow == fast) break;        if(slow->next == NULL) return NULL;        slow = slow->next;        if(fast->next == NULL) return NULL;        fast = fast->next;        if(fast->next == NULL) return NULL;        fast = fast->next;    }    fast = head;    while(slow != fast){        slow = slow->next;        fast = fast->next;    }    return fast;}};

参考的博客:

1.sysucph,Linked List Cycle II
2.小虫不会飞_,LeetCode:Linked List Cycle && Linked List Cycle II

0 0