首页 > 其他 > 详细

leetcode--Linked List Cycle--判断链表是否有环

时间:2014-10-01 08:35:01      阅读:347      评论:0      收藏:0      [点我收藏+]

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

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


这个题目用快慢指针来做,重点在于代码怎么实现的简洁方便理解。

这里用快指针来判断链表是不是有NULL,没有NULL那再继续走,看是否能与慢指针遇上


class Solution {
public:
    bool hasCycle(ListNode *head) {
        ListNode *slow=head,*fast=head;
        while(fast!=NULL&&fast->next!=NULL)
        {
            slow=slow->next;
            fast=fast->next->next;
            if(slow==fast)
                return true;
        }
        return false;
    }
};


leetcode--Linked List Cycle--判断链表是否有环

原文:http://blog.csdn.net/u013011841/article/details/39706171

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