判断单链表是否有环

来源:互联网 发布:商陆花软件是什么 编辑:程序博客网 时间:2024/06/03 14:26

判断链表是否有环,若有,返回环的起始节点。

思路:快慢指针。若有环,则快慢指针必定相遇。

     public ListNode detectCycle(ListNode head) {        if(head == null){        return null;        }         ListNode fast = head;        ListNode slow = head;        while(fast!=null && fast.next!=null){        fast = fast.next.next;        slow = slow.next;        if(fast == slow){//说明有环,此时的fast和slow相遇点不一定是环的入口点        slow = head;        while(fast != slow){        fast = fast.next;        slow = slow.next;        }        return fast;        }        }                return null;    }


原创粉丝点击