首页 > 其他 > 详细

Linked List Cycle

时间:2014-10-14 23:44:30      阅读:262      评论: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         struct ListNode *slow = head;
 5         struct ListNode *fast = head;
 6         
 7         while (fast != NULL && fast->next != NULL) {
 8             slow = slow->next;
 9             fast = fast->next->next;
10             
11             if (slow == fast) {
12                 return true;
13             }
14         }
15         return false;
16     }
17 };

 

Linked List Cycle

原文:http://www.cnblogs.com/skycore/p/4025379.html

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