- 遍历链表,判断节点 p->next 为null, 就到了链表最后
- map,标记访问过节点,重复访问有环
class Solution{
public:
bool hasCycle(ListNode *head){
unordered_map<ListNode*,bool>m;
while(head){
if(m.find(head) != m.end()) return true;
m[head] = true;
head = head->next;
}
return false;
}
};
- 一快一慢俩个节点,一个快一个慢,只要相遇就是有环
class Solution {
public:
bool hasCycle(ListNode *head) {
if (head == NULL){
return false;
}
ListNode *fast = head;
ListNode *slow = head;
while ( fast != NULL && slow !=NULL && fast->next != NULL ){
slow = slow->next;
fast = fast->next->next;
if (fast == slow){
return true;
}
}
return false;
}
};
网友评论