zoukankan      html  css  js  c++  java
  • 判断单链表是否有环

    判断单链表是否有环

    单链表有环指的是单链表中某个节点的next域指向链表中在它之前的某一个节点,这样在链表的尾部形成一个环形结构。

    代码实现

    package 剑指offer;

    import java.util.HashSet;
    import java.util.List;

    /**
     * @author WangXiaoeZhe
     * @Date: Created in 2019/11/22 16:55
     * @description:
     */

    public class Main13 {
        public static void main(String[] args) {

        }


        class ListNode {
            int val;
            ListNode next;

            ListNode(int x) {
                val = x;
                next = null;
            }
        }

        /**
         * 利用set的性质
         * @param head
         * @return
         */

        public boolean hasCycle(ListNode head){
            /**
             * 创建集合对象
             */

            HashSet<ListNode> set = new HashSet<>();
            /**
             * 遍历链表
             */

            ListNode p=head;
            while(p!=null){
                if (set.contains(p)) {
                    return true;
                } else {
                    set.add(p);
                }
                p=p.next;
            }
            return false;
        }

        /**
         * 快慢指针遍历法
         */

        public boolean hasCycle2(ListNode head) {
            if (head == null || head.next == null) {
                return false;
            }
            ListNode fast=head;
            ListNode slow=head;
            while (fast != null && fast.next != null) {
                slow=slow.next;
                fast=fast.next.next;
                if (slow == fast) {
                    return true;
                }
            }
            return false;
        }

    }
  • 相关阅读:
    Redis与Memcached汇总
    那些年掉进的坑之AngularJS篇
    常见的Regex表达式(更新RFC标准的email检验)
    让IE6 IE7 IE8 IE9 IE10 IE11支持Bootstrap的解决方法
    Windows + Android + Cordova + ionic环境搭建
    less语法
    AngularJS 指令之 ng-style
    AngularJS 指令之 ng-if
    ionic之自定义 ion-tabs 图标
    AngularJS之延迟加载html template
  • 原文地址:https://www.cnblogs.com/wuhen8866/p/11912671.html
Copyright © 2011-2022 走看看