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

Linked List Cycle II

时间:2015-04-09 06:27:21      阅读:120      评论:0      收藏:0      [点我收藏+]

标签:

写了无数次,今天终于自己想明白了,但是好像还是记住后明白的

技术分享

plotting tool: http://flowchart.com/

public class Solution {
    public ListNode detectCycle(ListNode head) {
        if(head==null|| head.next==null) return null;
        ListNode run = head, walk = head;
        while(run!=null){
            if(run.next!=null){
                run = run.next;
            }
            run = run.next;
            walk = walk.next;
            if(walk==run) break; // the "here"
        }
        if(run==null) return null; // 注意这里有个判断,可能根本没有循环
        walk = head;
        while(walk!=run){
            walk = walk.next;
            run = run.next;
        }
        return walk;
    }
}

 

Linked List Cycle II

标签:

原文地址:http://www.cnblogs.com/jiajiaxingxing/p/4407774.html

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