问题描述:
给定一个链表,判断链表中是否有环。
class Solution {
public:
bool hasCycle(ListNode *head) {
if(head==NULL) return false;
set<ListNode*> list;
while(head != NULL){
if(list.count(head))
return true;
else list.insert(head);
head = head->next;
}
return false;
}
};
使用一个集合
class Solution {
public:
bool hasCycle(ListNode *head) {
if(head==NULL) return false;
ListNode *fast,*slow;
fast = head->next;
slow = head;
while(fast!=slow){
if(fast==NULL || fast->next==NULL){
return false;
}
slow = slow->next;
fast = fast->next->next;
}
return true;
}
};
或者使用双指针