zoukankan      html  css  js  c++  java
  • LeetCode -- 推断链表中是否有环


    思路:

    使用两个节点。slow和fast,分别行进1步和2步。假设有相交的情况,slow和fast必定相遇;假设没有相交的情况,那么slow或fast必定有一个为null


    相遇时有两种可能:
    1. 仅仅是节点相交的情况,即:slow == fast可是 slow.next != fast.next
    2. 链表中存在环,即slow == fast 并且 slow.next == next


    实现代码:





    public bool HasCycle(ListNode head) {
            // - for null node , false
            if(head == null || head.next == null){
                return false;
            }
            if(head.val != head.next.val && head.next.next == null){
                return false;
            }
            
            var slow = head; 
            var fast = head;
    
    
            while(true) {
                slow = slow.next;
                if(fast.next != null){
                    fast = fast.next.next;
                }
                else{
                    return false;
                }
                
                if(slow == null || slow.next == null || fast == null || fast.next == null) {
                    return false;
                }
                
                if(slow.val == fast.val && slow.next.val == fast.next.val){
                    return true;
                }
            }
            return false;
        }


  • 相关阅读:
    ACM算法
    过度拟合的问题
    多类分类:一对多
    先进的优化
    简化成本函数和梯度下降
    对数回归的成本函数
    决策边界
    假设表示
    分类
    hdu1574 I Hate It (线段树,查询区间最大值)
  • 原文地址:https://www.cnblogs.com/wzjhoutai/p/6741763.html
Copyright © 2011-2022 走看看