Linked List Cycle - LeetCode

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 };

 

posted @ 2015-10-24 11:27  fenshen371  阅读(121)  评论(0)    收藏  举报