zoukankan      html  css  js  c++  java
  • Linked List Cycle——LeetCode

    Given a linked list, determine if it has a cycle in it.

    Follow up:
    Can you solve it without using extra space?

    题目大意:给定一个链表,判断是否有环?

    解题思路:

    解法一:快慢指针,如果有环,那么快慢指针总会相遇,有环;否则快的遍历完整个链表,无环。

    解法二:HashSet保存节点,如果下一个节点在set中出现过,那么有环,否则直到遍历完整个链表,无环。

    Talk is cheap>>

    解法一:

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

    解法二:

        public boolean hasCycle2(ListNode head) {
            if (head == null || head.next == null) {
                return false;
            }
            Set<ListNode> set = new HashSet<>();
            while (head != null) {
                if (set.contains(head)) {
                    return true;
                }
                set.add(head);
                head = head.next;
            }
            return false;
        }
  • 相关阅读:
    Part 29 AngularJS intellisense in visual studio
    Part 28 AngularJS default route
    css动画效果之一
    css
    css.盒子阴影
    css字行标签谁写写
    简单的介绍a标签点击个成
    看css.1的启示。
    css.1
    总结:html
  • 原文地址:https://www.cnblogs.com/aboutblank/p/4446675.html
Copyright © 2011-2022 走看看