Linked List Cycle II

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

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;

    }

}

 

你可能感兴趣的:(list)