Java for LeetCode 142 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?

解题思路,本题和上题十分类似,但是需要观察出一个规律,参考LeetCode:Linked List Cycle II

JAVA实现如下:

    public ListNode detectCycle(ListNode head) {
		ListNode fast = head, slow = head;
		boolean isLoop=false;
		while (fast != null) {
			slow = slow.next;
			ListNode temp = fast.next;
			if (temp == null)
				return null;
			fast = temp.next;
			if (fast == slow){
				isLoop=true;
				break;
			}
		}	
		while (isLoop) {
			if (slow == head)
				return slow;
			slow = slow.next;
			head = head.next;
		}
		return null;
    }

 

posted @ 2015-06-04 20:34  TonyLuis  阅读(168)  评论(0编辑  收藏  举报