如果链表中有某个节点,可以通过连续跟踪 next 指针再次到达,则链表中存在环。 为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。注意:pos 不作为参数进行传递,仅仅是为了标识链表的实际情况。
如果链表中存在环,则返回 true 。 否则,返回 false 。
进阶:
你能用 O(1)(即,常量)内存解决此问题吗?
题解方法一:
hash表遍历所有节点,每次遍历到一个节点时,判断该节点此前是否被访问过。
复杂度分析
时间复杂度:O(N),其中 N 是链表中的节点数。
空间复杂度:O(N),其中 NN 是链表中的节点数。主要为哈希表的开销,最坏情况下我们需要将每个节点插入到哈希表中一次。
count()返回集合中某个值元素的个数
/**
* 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) {
//使用hash表,遍历一次;
unordered_set<ListNode*> visited;
while(head!=NULL){
if(visited.count(head)==1){
return true;
}
visited.insert(head);
head=head->next;
}
return false;
}
};
题解方法二:使用快慢指针O(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,*slow=head;
while(fast!=slow){
if(fast==NULL||fast->next==NULL) return false;
fast=fast->next->next;
slow=slow->next;
}
return true;
}
};