给定一个链表,判断链表中是否有环。
为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。
示例 1:
输入:head = [3,2,0,-4], pos = 1
输出:true
解释:链表中有一个环,其尾部连接到第二个节点。
示例 2:
输入:head = [1,2], pos = 0
输出:true
解释:链表中有一个环,其尾部连接到第一个节点。
示例 3:
输入:head = [1], pos = -1
输出:false
解释:链表中没有环。
方法一:集合法
构造一个集合,集合收录链表的所有节点,当存在环时,必定会出现集合中出现重复的情况,此时返回true,遍历完没有出现重复,返回false
/**
* 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) {
unordered_set<ListNode*>myset;
ListNode*p=head;
while(p){
if(!myset.count(p)){
myset.insert(p);
}else{
return true;
}
p = p->next;
}
return false;
}
};
方法二:快慢指针法
设计两个指针,一个快指针,一个慢指针,当存在环时,慢指针肯定会追上快指针
python
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
if not head or not head.next:
return False
fast = head.next
slow = head
while fast != slow:
if not fast or not fast.next:
return False
slow=slow.next
fast = fast.next.next
return True