问题描述
Given head, the head of a linked list, determine if the linked list has a cycle in it.
There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail’s next pointer is connected to. Note that pos is not passed as a parameter.
Return true if there is a cycle in the linked list. Otherwise, return false.
给定一个链表,判断链表中是否有环。
如果链表中有某个节点,可以通过连续跟踪 next 指针再次到达,则链表中存在环。 为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。注意:pos不作为参数进行传递,仅仅是为了标识链表的实际情况。如果链表中存在环,则返回 true 。 否则,返回 false 。
思路
1.建立空hash表,遍历链表,逐个将链表元素加入到hash表中,如果当前元素在hash表中已经存在,则认为存在环。代码如下
class Solution {
public:
bool hasCycle(ListNode *head) {
unordered_set<ListNode*> visited;
while(head){
if(visited.count(head)) return true;
visited.insert(head);
head=head->next;
}
return false;
}
};
2.使用快慢指针,快指针一次前进两步,慢指针一次前进一步,当两个指针的位置有重合时,认为存在环。代码如下
class Solution {
public:
bool hasCycle(ListNode *head) {
auto slow=head;
auto fast=head;
while(fast) {
if(!fast->next) return false;
fast=fast->next->next;
slow=slow->next;
if(fast==slow) return true;
}
return false;
}
};
这里要注意,while(·)循环开始后,要首先判断fast的下一步是否是空,才能进行前进两步的操作。
快慢指针的算法原理如下图所示。