码迷,mamicode.com
首页 > 其他好文 > 详细

Linked List Cycle II

时间:2016-01-15 06:25:11      阅读:314      评论:0      收藏:0      [点我收藏+]

标签:

Given a linked list, return the node where the cycle begins.

If there is no cycle, return null.

Example

Given -21->10->4->5, tail connects to node index 1,return 10

Challenge

Follow up:

Can you solve it without using extra space?

 

///

 

/**
 * Definition for ListNode.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int val) {
 *         this.val = val;
 *         this.next = null;
 *     }
 * }
 */ 
public class Solution {
    /**
     * @param head: The first node of linked list.
     * @return: The node where the cycle begins. 
     *           if there is no cycle, return null
     */
    public ListNode detectCycle(ListNode head) {  
        // write your code here
        if(head==null ||head.next==null) return null;
        
        ListNode slow=head;
        ListNode fast=head;
        
        while(fast!=null || fast.next!=null)
        {
            fast=fast.next.next;
            slow=slow.next;
            
            if(fast==null|| fast.next==null) return null;
            
            if(fast==slow)
            break;
        }
        
        slow=head;
        while(slow!=fast)
        {
            slow=slow.next;
            fast=fast.next;
        }
        return fast;
    }
}

 

Linked List Cycle II

标签:

原文地址:http://www.cnblogs.com/kittyamin/p/5132182.html

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