How to tell if a single linked list has a ring

Source: Internet
Author: User
method A quick and slow node way, if the fast node meets with the slowly node proves to have a ring
    public int Hasloop (node node) {
        int hasloop = 0;
        Node Node1 = node;
        Node Node2 = node;
        while (Node2 = null &&! = null) {
            node1 =;
            Node2 =;
            if (Node1.equals (Node2)) {//Meet proof with ring
                hasloop = 1;
        return hasloop;
method 22 Nodes Node1 and Node2,node2 each time to start from the beginning, see if Node1 and Node2 walk the number of steps is consistent, if the inconsistency exists ring
 public int hasLoop2 (node node) {int hasloop = 0;
        int pos1 = 0;
        Node Node1 = node;
            while (Node1! = null) {node Node2 = node;
            int pos2 = 0;
                        while (node2! = null) {if (Node2.equals (Node1)) {//Encounters if (pos1! = Pos2) {//traversed path inconsistent proof ring
                        Hasloop = 1;
                    return hasloop;
                    }else {break;
                }} pos2++;
            Node2 =;
            } pos1++;

        Node1 =;
    } return Hasloop; }

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.