这道题用two pointers的方法也很巧妙,用一个slow pointer一次移动一步,一个fast pointer一次移动两步,如果有环,那么最终fast会和slow会和(用个简单例子比划下),如果没会和前fast或fast->next就到达了终点NULL,那么必是无环链表。这样能让空间复杂度是O(1)
naive的想法是用hash table储存所有已经访问过的节点
bool hasCycle(ListNode *head) {
if(head == NULL) return false;
unordered_set<ListNode *> st;
ListNode *p = head;
while(p != NULL) {
if(st.find(p) != st.end()) { //已有
return true;
}
else {
st.insert(p);
p = p->next;
}
}
return false;
}
下面是用two pointers的方法,注意slow起点是head, fast起点是head->next
bool hasCycle(ListNode *head) {
if(head == NULL || head->next == NULL) return false;
ListNode *slow = head;
ListNode *fast = head->next;
while(slow != fast) {
if(fast == NULL || fast->next == NULL) {
return false;
}
else {
slow = slow->next;
fast = fast->next->next;
}
}
return true;
}