解决方法有两种:
- 遍历链表,在map中记录遍历过的节点,遇到重复的返回
true
- 快慢指针,快指针移动速度为2,慢指针移动速度为1。
如果存在环,快慢指针会相遇。否则会走到空指针。
附上代码:
哈希表
class Solution {
public:
bool hasCycle(ListNode *head) {
map<ListNode*,int> m;
ListNode* node = head;
while(node && !m.count(node)){
m[node] = 0;
node = node->next;
}
if(!node) return false;
return true;
}
};
快慢指针
class Solution {
public:
bool hasCycle(ListNode *head) {
if(!head) return false;
ListNode* fast = head->next;
ListNode* slow = head;
while(fast != slow){
if(!fast || !slow) return false;
fast = fast->next;
if(fast) fast = fast->next;
slow = slow->next;
}
return true;
}
};