您的位置:首页 > 其它

LeetCode|Linked List Cycle II

2014-04-12 20:05 260 查看

题目

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?

思路

本来我傻傻的用 Linked List Cycle 的方法来做,以为找到了节点就意味着这个点就是环的开始。但是,结果报了个错

Input:{3,2,0,-4}, tail connects to node index 1
Output:tail connects to node index 3
Expected:tail connects to node index 1
我才意识到,环可能是在链表的中间链接起来!!!所以这种做法是错的.

于是换了另一个思路.

我们假设slow走了n步,而fast走了2n步.在环的某个点相遇(假设点D).那么,想一下.如果让fast不动,让slow在走n步,slow是不是刚好又回到了这个相遇点(D)?(因为fast走了2n步到达这个地方).那么此时,如果让fast也从链表的开头走,走n步.那么fast和slow必定会在D相遇.但是,这之前,它们就会提前相遇,而相遇点就是环入口!

代码

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode detectCycle(ListNode head) {
		ListNode node = null;
		if(head == null)
			return node;
		ListNode quick = head;
		ListNode slow = head;
		
		boolean tag = false;
		while(quick!=null &&quick.next != null)
		{
			quick = quick.next;
			quick = quick.next;
			slow = slow.next;
			if(quick == slow)
			{
				tag = true;
				break;
			}
		} 
		
		if( tag  == false)
		{
			return node;
		}
		else
		{
			quick = head;
			while( true)
			{
				if( quick == slow)
				{
					return quick;
				}
				else
				{
					quick = quick.next;
					slow = slow.next;
				}
			}
		}
    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: