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));
        }
  • 相关阅读:
    JavaBean理解
    你应该掌握的七种回归技术
    回归分析步骤
    rsync命令(同步/备份数据)
    获取客户端访问的ip地址
    SSO单点登陆
    产品分类之属性选择
    linux的SVN搭建与同步
    php 实现 mysql数据表优化与修复
    php程序备份还原mysql数据库
  • 原文地址:https://www.cnblogs.com/use-D/p/13296789.html
Copyright © 2011-2022 走看看