zoukankan      html  css  js  c++  java
  • 快慢指针算法-判断单向链表是否有环

    判断单链表是否有环,如果有环的话,具体再有环的节点是哪个?

        static class Node {
            private Node next;
            private int val;
    
            public Node(Node next, int val) {
                this.next = next;
                this.val = val;
            }
    
            public Node getNext() {
                return next;
            }
    
            public void setNext(Node next) {
                this.next = next;
            }
    
            public int getVal() {
                return val;
            }
    
            public void setVal(int val) {
                this.val = val;
            }
    
            @Override
            public boolean equals(Object o) {
                if (this == o) return true;
                if (o == null || getClass() != o.getClass()) return false;
                Node node = (Node) o;
                return val == node.val &&
                        Objects.equals(next, node.next);
            }
        }
    
        public static void main(String[] args) {
            Node node1 = new Node(null, 1);
            Node node2 = new Node(node1, 2);
            Node node3 = new Node(node2, 3);
            Node node4 = new Node(node3, 4);
            Node node5 = new Node(node4, 5);
            Node node6 = new Node(node5, 6);
            Node node7 = new Node(node6, 7);
            Node node8 = new Node(node7, 8);
            Node tail = new Node(node8, 9);
            node1.setNext(node4);
    
            Node slow = tail;
            Node fast = tail;
            int count = 1;
            slow = slow.next;
            fast = fast.next.next;
            while (slow.val != fast.val) {
                count++;
                slow = slow.next;
                fast = fast.next.next;
            }
    
            System.out.println(JSON.toJSONString(slow.val) + ";count=" + count);
            slow = tail;
            slow = slow.next;
            fast = fast.next;
            while (slow.val != fast.val) {
                slow = slow.next;
                fast = fast.next;
            }
            System.out.println(JSON.toJSONString(slow.val));
        }
  • 相关阅读:
    IDEA操作git的一些常用技巧
    实现多Realm时,可能会出现的问题
    Solr入门-Solr服务安装(windows系统)
    ES6中的Set和Map集合
    ES6中的类
    ES6数组扩展
    ES6定型数组
    Promise和异步编程
    深入理解ajax系列第八篇
    深入理解ajax系列第六篇
  • 原文地址:https://www.cnblogs.com/use-D/p/13296789.html
Copyright © 2011-2022 走看看