标签:
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 };
标签:
原文地址:http://www.cnblogs.com/fenshen371/p/4906483.html