首页 > 其他 > 详细

【LeetCode】Linked List Cycle

时间:2015-07-30 22:48:53      阅读:182      评论:0      收藏:0      [点我收藏+]

称号

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

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

解答

首先要注意空链表不成环;不能开额外的空间,即空间复杂度是o(1),可採用“快慢指针”查检查链表是否含有环,假设在快的指针可以追上慢的指针,则有环。否则无环。

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public boolean hasCycle(ListNode head) {
        if(head==null){
            return false;
        }
        ListNode fast=head;
        ListNode slow=head;
        while(fast!=null&&fast.next!=null){  //仅仅要推断快指针是否为空就能够了,可是注意当fast是为结点时,fast.next为空。若推断fast.next.next则会报NullPointerException
            slow=slow.next;
            fast=fast.next.next;
            if(slow==fast){
                return true;
            }
        }
        return false;
    }
}


---EOF---

版权声明:本文博客原创文章。博客,未经同意,不得转载。

【LeetCode】Linked List Cycle

原文:http://www.cnblogs.com/yxwkf/p/4690737.html

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