给定一个链表,判断链表中是否有环。
为了表示给定链表中的环,我们使用整数 pos
来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos
是 -1
,则在该链表中没有环。用双指针来实现:当a和b没相遇,到了空时返回-1,相遇时,如果a下一个位置和b的位置不在head节点上就返回1表示有环,若在head节点上则返回0表示头尾环相连。
# 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
"""
a=ListNode(0)
b=ListNode(0)
a.next=head
b.next=head
a.next=head.next
b.next=head.next.next
while a!=b:
if b==None and b.next==None:
return False
else:
a=a.next
b=b.next.next
if a==head :
return 0
else :
return True