首页 > 其他 > 详细

Linked List Cycle

时间:2015-11-10 11:59:15      阅读:216      评论:0      收藏:0      [点我收藏+]

题目:

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

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

解析:

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

注意:开始while的判断语句写成了

fast->next && fast
 

这是万万不可的,因为&&运算首先要判断前者,万一fast不存在,判断fast->next将会超时

 

Linked List Cycle

原文:http://www.cnblogs.com/raichen/p/4952334.html

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