2014年4月28日 星期一

[LeetCode] Linked List Cycle II

Problem:
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?
Solution:O(n)
public class Solution {
    public ListNode detectCycle(ListNode head) {
        
        if(head == null || head.next == null)
            return null;
        ListNode fast = head;
        ListNode slow = head;
        ListNode ret = head;
        while(fast !=null && fast.next!=null){
            fast = fast.next.next;
            slow = slow.next;
            if(fast == slow){
                while(ret != slow){
                ret = ret.next;
                slow = slow.next;
                }
                return ret;
} } return null; } }

沒有留言:

張貼留言