Skip to main content
 首页 » 编程设计

java算法之单链表应用(2)使用快慢指针,如何判断是否有环,环在哪个节点

2022年07月18日25cyq1162
//单链表的使用:快慢指针,如何判断是否有环,环在哪个节点 
    public static void main(String[] args) { 
        Node<Integer> node1 = new Node(1,null); 
        Node<Integer> node2 = new Node(2,null); 
        Node<Integer> node3 = new Node(3,null); 
        Node<Integer> node4 = new Node(4,null); 
        Node<Integer> node5 = new Node(5,null); 
        Node<Integer> node6 = new Node(6,null); 
        node1.next = node2; 
        node2.next = node3; 
        node3.next = node4; 
        node4.next = node5; 
        node5.next = node6; 
        node6.next = node4; //产生环 
 
        Node quick = node1.next.next; 
        Node low = node1.next; 
        while (!quick.equals(low)){ 
            quick = quick.next.next; 
            low = low.next; 
        } 
        System.out.println("有环,继续找环"); 
        Node low2 = node1; 
        while (!low2.equals(low)){ 
            low = low.next; 
            low2 = low2.next; 
        } 
        System.out.println("环的节点值是:" + low2.t); 
    } 
 
    private static class Node<T>{ 
        private T t; 
        private Node next; 
 
        public Node(T t, Node next) { 
            this.t = t; 
            this.next = next; 
        } 
    }

本文参考链接:https://www.cnblogs.com/maohuidong/p/14216293.html