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?

分析:用map记录是否出现过。

用时:60ms

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     bool hasCycle(ListNode *head) {
12         if(!head || !head->next) return false;
13         
14         map<ListNode*, bool> m;
15         while(head){
16             if(m.find(head) == m.end()) m[head] = true;
17             else return true;
18             head = head->next;
19         }
20         return false;
21     }
22 };

 

看到比较好的方法:设置两个指针,一个快(每次走两步),一个慢(每次走一步)。如果快慢指针相遇,那么表示有环,否则无环。

用时16ms。远优于使用map的方式。

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     bool hasCycle(ListNode *head) {
12         if(!head || !head->next) return false;
13         
14         ListNode *fast = head, *slow = head;
15         while(fast && fast->next){
16             fast = fast->next->next;
17             slow = slow->next;
18             if(fast == slow) return true;
19         }
20         return false;
21     }
22 };
posted @ 2015-05-20 21:38  amazingzoe  阅读(131)  评论(0编辑  收藏  举报