leetcode解题: Linked List Cycle (141)

Given a linked list, determine if it has a cycle in it.

Follow up:
Can you solve it without using extra space?

解法1:O(1) Space + O(N) Time, Two pointers

此题初看可以用hashtable来解决,用一个指针一边跑一边放入hashtable,如果跑到见过的node⑩则知道有cycle。
由于follow up中提到了不能用extra space,所以考虑经典的two pointers算法。快慢指针,一个走一步一个走两步,如果在走完之前相遇的话就有cycle。
要注意的是输入的判定,如果为空list的话直接返回false
C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool hasCycle(ListNode *head) {
if (head == NULL) {
return false;
}
ListNode* slow = head;
ListNode* fast = head->next;
while (fast != NULL && fast->next != NULL) {
slow = slow->next;
fast = fast->next->next;
if (slow == fast) {
return true;
}
}
return false;
}
};

Java

1