码迷,mamicode.com
首页 > 其他好文 > 详细

Linked List Cycle - LeetCode

时间:2015-10-24 12:54:25      阅读:154      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!