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?

思路:

快慢指针。两个指针同时从head出发,一个每次加一,一个每次加二,如果相遇的话就存在环。

代码

 1     bool hasCycle(ListNode *head) {
 2         // IMPORTANT: Please reset any member data you declared, as
 3         // the same Solution instance will be reused for each test case.
 4         if(head == NULL)
 5             return false;
 6         if(head->next == NULL)
 7             return false;
 8         ListNode *slow = head, *fast = head;
 9         while(true){
10             if(fast && fast->next){
11                 fast = fast->next->next;
12             }
13             else{
14                 return false;
15             }
16             slow = slow->next;
17             if(fast == slow)
18                 return true;
19         }
20     }

 

posted on 2013-11-03 10:02  waruzhi  阅读(110)  评论(0编辑  收藏  举报

导航