题目:
给定一个链表,判断链表中是否有环。
为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。
示例 1:
输入:head = [3,2,0,-4], pos = 1
输出:true
解释:链表中有一个环,其尾部连接到第二个节点。
思路:
1.因为链表只有一个前驱和一个后继,所以如果链表有环,则该环必然是由最后一个节点形成的。设置快两个快慢指针,对于一个有环的跑道,慢的人和快的人必然会相遇。同理,设置两个不同步长的指针,两个指针在环形链表中也必然相遇。
2.哈希表,此处可用list代替,只存节点
代码:
方法1
# 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
"""
low=head
fast=head
if head is None :
return False
# while low.next and fast.next.next:快指针肯定比慢指针快,只需判断快指针的next和next.next
while fast.next and fast.next.next:
fast=fast.next.next#步长为2
low=low.next#步长为1
if fast==low:
return True
return False
方法2:
# 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
"""
map_=[]
while head:
if head in map_:
return True
else:
map_.append(head)
head=head.next
return False