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;
        }

    }
  • 相关阅读:
    利用git上传到码云
    js 数组的方法总结
    什么是浏览器的回流和重绘以及如何减少回流和重绘
    数组的方法some和includes
    node.js中使用http-proxy-middleware请求转发给其它服务器
    什么是BFC
    如何用Github上传项目中的代码
    前端渲染与后端渲染的区别有哪些
    移动端路由的切换
    面试题
  • 原文地址:https://www.cnblogs.com/wuhen8866/p/11912671.html
Copyright © 2011-2022 走看看