给你一个链表的头节点 head
,判断链表中是否有环。
1.快慢指针
一个快指针一次走两格,慢指针一次走一格,如果存在闭环的话快慢指着早晚会相遇
/**
* 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||head->next==NULL){
return false;
}
ListNode *fast=head->next;
ListNode *slow=head;
while(slow!=fast){
if(fast==NULL||fast->next==NULL){
return false;
}
fast=fast->next->next;
slow=slow->next;
}
return true;
}
};
2.哈希表遍历
可以使用哈希表来存储所有已经访问过的节点。每次我们到达一个节点,如果该节点已经存在于哈希表中,则说明该链表是环形链表,否则就将该节点加入哈希表中。重复这一过程,直到我们遍历完整个链表即可。
/**
* 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) {
set<ListNode*> s;
while(head!=NULL){
if(s.count(head)){
return true;
}
s.insert(head);
head=head->next;
}
return false;
}
};