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

    Question:

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

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

    Analysis:

    思路一:快慢指针法。前面用到过快慢指针寻找链表的中间节点。若快慢指针会相遇,则说明有环;否则快指针遇到null,则说明无环。

    Answer:(Beats 100% java submission~)

    public class Solution {
        public boolean hasCycle(ListNode head) {
            if(head == null)
                return false;
            ListNode fast = head, slow = head;
            while(fast.next != null || fast == null) {
                if(fast.next == null || fast == null || fast.next.next == null)
                    return false;
                slow = slow.next;
                fast = fast.next.next;
                if(slow == fast)
                    return true;
            }
            return false;
        }
    }
  • 相关阅读:
    ProjectEuler 13
    ProjectEuler 8
    ProjectEuler 5
    ProjectEuler 6
    ProjectEuler 7
    ProjectEuler 9
    日程管理系统维护改善1
    日程管理系统改错
    android作业Text
    四则运算
  • 原文地址:https://www.cnblogs.com/little-YTMM/p/4803579.html
Copyright © 2011-2022 走看看