141.Linked List Cycle

版权声明:转载请注明出处--mosterRan https://blog.csdn.net/qq_35975685/article/details/86581790

给定一个链表,判断链表中是否有环。

为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。
git源码地址:https://github.com/a947000098/algorithm-case

 /**
     *  一个链表怎么看是否有环
     *  第一种:如果一个链表一秒钟后走到了null那么就说明没有环 延迟1s
     *  第二种:使用一个Set数据结构,每次遍历结点的时候都添加进去,如果发现添加进去原来有了那么就说明有环
     *  第三种:快慢指针 慢指针走一步,快指针走两步,当快慢指针相遇则说明有环
     *
     */
public static boolean hasCycleOne(ListNode head) {
        long startTime = System.currentTimeMillis();
        while(head.next != null){
            head = head.next;
            long nowTime = System.currentTimeMillis();
            if(nowTime - startTime > 2000){
                return true;
            }
        }
        return false;
    }

    /**
     * 这是判断是否有环的第二种(前提是所有val不重复)
     * @param head
     * @return
     */
    public static boolean hasCycleTwo(ListNode head) {
        Set set = new HashSet();
        while(head != null){
            if(!set.contains(head.val)){
                set.add(head.val);
            }else {
                return true;
            }
            head = head.next;
        }
        return false;
    }
 /**
     * 判断是否有环的第三种 快慢指针
     * @param head
     * @return
     */
    public static boolean hasCycleThree(ListNode head) {
        if(head == null){
            return false;
        }
        ListNode fast = head;
        ListNode slow = head;
        while(fast.next != null && fast.next.next != null){
            slow = slow.next;
            fast = fast.next.next;
            if(slow == fast){
                return true;
            }
        }
        return false;
    }

猜你喜欢

转载自blog.csdn.net/qq_35975685/article/details/86581790