leetcode-142. Linked List Cycle II

142. Linked List Cycle II

Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

Note: Do not modify the linked list.

Follow up:
Can you solve it without using extra space?

题意:

142. Linked List Cycle II的基础上,找到环起点的位置。

就是利用287. Find the Duplicate Number的思路,在287题的基础上,判断是否会 不能构成环 即可。具体思路可以去看一下 287题

public class Solution {
public ListNode detectCycle(ListNode head) {
if (head == null) return null;
ListNode slow = head;
ListNode fast = head;
while (fast != null && fast.next != null){
slow = slow.next;
fast = fast.next.next;
if (fast == slow)
break;
}
if (fast == null || fast.next == null) return null;
fast = head;
while (fast != slow){
fast = fast.next;
slow = slow.next;
}
return fast;
}
}
posted @ 2018-01-03 22:09  link98  阅读(116)  评论(0编辑  收藏  举报