码迷,mamicode.com
首页 > 编程语言 > 详细

Java for LeetCode 142 Linked List Cycle II

时间:2015-06-04 21:02:52      阅读:151      评论:0      收藏:0      [点我收藏+]

标签:

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;
    }

 

Java for LeetCode 142 Linked List Cycle II

标签:

原文地址:http://www.cnblogs.com/tonyluis/p/4552909.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!