Linked List Cycle

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) {
 5             return false;
 6         }
 7         ListNode* slow = head;
 8         ListNode* fast = head;
 9         while (slow && fast) {
10             slow = slow->next;
11             if (!fast->next) {
12                 return false;
13             }
14             fast = fast->next->next;
15             if (slow == fast) {
16                 return true;
17             }
18         }
19         return false;
20     }
21 };

 

posted @ 2014-04-04 23:53  beehard  阅读(106)  评论(0编辑  收藏  举报