LeetCode——Linked List Cycle II

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?

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

题目:给定一个链表。返回环開始的节点。如无环。返回null.

	public ListNode detectCycle(ListNode head) {
		ListNode fast = head,slow = head;
		while(fast != null && fast.next != null){
			slow = slow.next;
			fast = fast.next.next;
			if(slow == fast)
				break;
		}
		if(fast == null || fast.next == null )
			return null;
		slow = head;
		while(slow != fast){
			slow = slow.next;
			fast = fast.next;
		}
		return slow;
	}
	// Definition for singly-linked list.
	class ListNode {
		int val;
		ListNode next;

		ListNode(int x) {
			val = x;
			next = null;
		}
	}

以下的文章总结得非常好。

学习了。

寻找环存在和环入口的方法:

用两个指针p1、p2指向表头。每次循环时p1指向它的后继,p2指向它后继的后继。

若p2的后继为NULL,表明链表没有环。否则有环且p1==p2时循环能够终止。此时为了寻找环的入口,将p1又一次指向表头且仍然每次循环都指向后继。p2每次也指向后继。

当p1与p2再次相等时,相等点就是环的入口。


參考:http://www.cnblogs.com/wuyuegb2312/p/3183214.html

版权声明:本文博客原创文章。博客,未经同意,不得转载。