首页 > 其他 > 详细

Linked List Cycle

时间:2015-03-04 15:56:33      阅读:244      评论:0      收藏:0      [点我收藏+]

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的妙用 可以进行一次判断了

Linked List Cycle

原文:http://www.cnblogs.com/sunshisonghit/p/4313324.html

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