• 判断单链表是否有环


    判断单链表是否有环

    单链表有环指的是单链表中某个节点的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;
        }

    }
  • 相关阅读:
    Linux基础---开关机与帮助
    Linux磁盘管理命令
    批处理之命令补充II
    LeetCode 328. 奇偶链表(Odd Even Linked List)
    LeetCode 岛屿的最大面积(探索字节跳动)
    LeetCode 复原IP地址(探索字节跳动)
    LeetCode 简化路径(探索字节跳动)
    LeetCode 最长公共前缀(探索字节跳动)
    LeetCode 无重复字符的最长子串(探索字节跳动)
    自动机器学习超参数调整(贝叶斯优化)
  • 原文地址:https://www.cnblogs.com/wuhen8866/p/11912671.html
Copyright © 2020-2023  润新知