首页 > 其他 > 详细

Linked List Cycle

时间:2015-03-13 01:36:18      阅读:227      评论:0      收藏:0      [点我收藏+]

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

简单题,只要知道快慢指针这个技巧就很容易解了。

 

 1 class Solution {
 2 public:
 3     bool hasCycle(ListNode *head) {
 4         if(head == NULL)
 5         return false;
 6         ListNode* slow=head; ListNode* fast=head;
 7         while(fast->next!=NULL && fast->next->next!=NULL){
 8             fast=fast->next->next;
 9             slow=slow->next;
10             if(fast == slow)
11             return true;
12         }
13         return false;
14     }
15 };

 

但是要注意几个空指针的判断。

 

Linked List Cycle

原文:http://www.cnblogs.com/desp/p/4334103.html

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