【数据结构与算法】05. java 判断链表是否有环,求环长(快慢指针)

判断单链表是否有环,我们可以想一想我们平时在操场跑步,有的人跑的快,有的人跑的慢,你会发现,跑的快的人,总会超过走的慢的人。判断链表是否有环也是这个道理,慢指针每次移动一个位置,快指针每次移动两个位置,若有环,快指针一定能和慢指针相遇,相反,如果没有环,永远无法相遇。

package com.fjx.learn;

public class Node {
    public int data;
    public Node next;

    public Node(int data, Node next) {
        this.data = data;
        this.next = next;
    }

    public int getData() {
        return data;
    }
}

package com.fjx.learn;

public class CheckRing {

    public static void main(String[] args) {
        // 前一个节点,指向后一个节点
        Node node5 = new Node(5, null);
        Node node4 = new Node(4, node5);
        Node node3 = new Node(3, node4);
        Node node2 = new Node(2, node3);
        Node node1 = new Node(1, node2);
        // 让第五元素指向第一个元素,此时形成了一个环。
        node5.next = node1;

        System.out.println("是否有环");
        // System.out.println(hasLoop(node1).getData());
        if(hasLoop(node1)!=null)
        {
            System.out.println("有");
        }
        else{
            System.out.println("无");
        }

        System.out.println("环的长度-------" +hasLoopLength(node1));
    }

    // 判断单链表是否有环
    public static Node hasLoop(Node linklist) {
        // 判断链表是否为空
        if (linklist == null) {
            return null;
        }
        Node slow = linklist;
        Node fast = linklist;
        // 说明有环
        while (fast.next != null && fast.next.next != null) {
           // 指针进行移动,慢指针每次移动一位,快指针每次移动两位
            slow = slow.next;
            fast = fast.next.next;
            
           // 快慢指针相遇,说明有环
            if (slow == fast) {
                // 返回当前节点
                return slow;
            }
        }
        return null;
    }

    // 输出单链表的环的长度
    public static long hasLoopLength(Node list) {
        // 判断是否有环,如果有,返回相遇点
        Node temp = hasLoop(list);
        Node temp1 = temp;
        // 返回值为null,说明单链表无环,且长度为0
        if (temp == null) {
            return 0;
        }
        // 记录指针走过的次数,当慢指针再次走到相遇的位置,就是环的长度了。
        long loopLength = 0;
        do {
            temp = temp.next;
            loopLength++;
        } while (temp1 != temp);

        // 返回环的长度
        return loopLength;

    }
}

求 链表环长你知道了么?

发布了250 篇原创文章 · 获赞 461 · 访问量 12万+

猜你喜欢

转载自blog.csdn.net/fjxcsdn/article/details/105350717