Linked List Cycle II

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

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;
    }
}

 

posted @ 2015-04-09 05:07  世界到处都是小星星  阅读(103)  评论(0编辑  收藏  举报