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

[LeetCode]142 Linked List Cycle II

时间:2015-01-09 01:51:33      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:leetcode

https://oj.leetcode.com/problems/linked-list-cycle-ii/

http://blog.csdn.net/linhuanmars/article/details/21260943

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode detectCycle(ListNode head) {
        
        if (head == null)
            return null;
            
        ListNode one = head;
        ListNode two = head;
        
        ListNode meet = null;
        while (one != null && two != null)
        {
            one = one.next;
            two = two.next;
            
            if (two == null)
                return null;
            else
                two = two.next;
            
            if (one == two)
            {
                meet = one;
                break;
            }
        }
        
        if (meet == null)
            return null; // no cicle.
        
        one = head;
        while (one != two)
        {
            one = one.next;
            two = two.next;
        }
        return one;
    }
}


[LeetCode]142 Linked List Cycle II

标签:leetcode

原文地址:http://7371901.blog.51cto.com/7361901/1600801

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