首页 > 其他 > 详细

Linked List Cycle - LeetCode

时间:2015-10-24 12:52:54      阅读:170      评论: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         if (head == NULL) return false;
 5         ListNode *slow = head;
 6         if (head->next == NULL) return false;
 7         ListNode *fast = head->next;
 8         while (slow != fast)
 9         {
10             if (slow != NULL)
11                 slow = slow->next;
12             if (fast != NULL)
13                 fast = fast->next;
14             if (fast != NULL)
15                 fast = fast->next;
16         }
17         return slow != NULL;
18     }
19 };

 

Linked List Cycle - LeetCode

原文:http://www.cnblogs.com/fenshen371/p/4906483.html

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