[LeedCode OJ]#142 Linked List Cycle II

【 声明:版权所有,转载请标明出处,请勿用于商业用途。  联系信箱:[email protected]


题目链接:https://leetcode.com/problems/linked-list-cycle-ii/


题意:

对于一个链表,判断其是否有环,有环则返回环的起始位置。


思路:

通过141题,我们知道可以通过快慢指针来判断是否有环,现在我们假设两个指针相遇在z点,如图


那么我们可以知道fast指针走过a+b+c+b

slow指针走过a+b

那么2*(a+b) = a+b+c+b

所以a = c

那么此时让slow回到起点,fast依然停在z,两个同时开始走,一次走一步

那么它们最终会相遇在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 = head;
			ListNode *fast = head;
			do
			{
				if(!slow||!fast)
					return nullptr;
				slow = slow->next;
				fast = fast->next;
				if(fast)
					fast = fast->next;
				else
					return nullptr;
			}
			while(slow!=fast);

			slow = head;
			while(slow!=fast)
			{
				slow = slow->next;
				fast = fast->next;
			}
			return slow;
		}
};



你可能感兴趣的:(LeedCode,OJ,LeetCode刷题之路)