LeetCode Linked List Cycle II

来源:互联网 发布:淘宝蓝冠店赚钱 编辑:程序博客网 时间:2024/06/05 15:32

题目描述: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.

若存在环则输出环的起点,若不存在则输出NULL。由于是在判断环的基础上输出环的起点,因此仍使用Linked List Cycle的思路,然后在此基础上计算起点。

1.判断链表有无环

可以类比追击问题,使用两个移动速度不一样的指针,快指针每次比慢指针多走一步。若链表无环,则快指针会先走到终点;否则当快指针经过尾部之后,就由领先变成落后,则一定会追上慢指针。

2.求环的起点


设相遇时慢指针走了t步,则快指针走了2t步,起始时少走一步,但从尾部到环起始多花一步,所以比慢指针多走的t步即为环的长度。由上图可知,从head到begin的步数等于从encounter到tail的步数,而tail再走一步就是begin。所以可以利用此关系得到begin。代码如下:

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


0 0