您的位置:首页 > 编程语言 > Java开发

Java for LeetCode 142 Linked List Cycle II

2015-06-04 20:34 686 查看
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: