首页 > 其他 > 详细

LeetCode -- 推断链表中是否有环

时间:2017-04-21 09:26:32      阅读:160      评论:0      收藏:0      [点我收藏+]

思路:

使用两个节点。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;
    }


LeetCode -- 推断链表中是否有环

原文:http://www.cnblogs.com/wzjhoutai/p/6741763.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!