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

    Linked List Cycle

    问题:

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

    思路:

    快指针,慢指针方法

    我的代码:

    public class Solution {
        public boolean hasCycle(ListNode head) {
            if(head == null || head.next == null)
                return false ;
            ListNode one = head ;
            ListNode two = head.next.next ;
            while(one != null && two != null)
            {
                if(one == two)
                    return true ;
                one = one.next ;
                if(two.next == null)
                    break ;
                two = two.next.next ;
            }
            return false ;
            
        }
    }
    View Code

    他人代码:

    public class Solution {
        public boolean hasCycle(ListNode head) {
            if (head == null) {
                return false;
            }
    
            ListNode fast = head, slow = head;
            do {
                if (fast.next == null || fast.next.next == null) {
                    return false;
                }
                fast = fast.next.next;
                slow = slow.next;
            } while (fast != slow);
    
            return true;
        }
    }
    View Code

    学习之处:

    • 如果没有cycle,快指针肯定先到null
    • do while的妙用 可以进行一次判断了

    if(null==node || node.next==null) return false;

    ListNode slowNode = node;
    ListNode fastNode = node.next.next;

    while(fastNode!=null && fastNode.next!=null){
    if(slowNode == fastNode) return true;
    slowNode = slowNode.next;
    fastNode = fastNode.next.next;
    }

    return false;

  • 相关阅读:
    p3201&bzoj1483 梦幻布丁
    p1341 无序字母对
    p2590&bzoj1036 树的统计
    p1462 通往奥格瑞玛的道路
    p1522 牛的旅行 Cow Tours
    ARC097D Equals
    p2371&bzoj2118 墨墨的等式
    ARC097C K-th Substring
    欧拉函数入门合集(模板)
    主席树
  • 原文地址:https://www.cnblogs.com/sunshisonghit/p/4313324.html
Copyright © 2011-2022 走看看