给定一个链表,判断链表中是否有环。
为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。
解法1:直接法
思路:遍历链表,将已经经过的位置存入target数组,如果遍历位置指向的下一个值位置在target数组中,说表构成环形链表
# 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 head == None:
reutnr False
target = {head}
head = head.next
while head:
if head in target:
return True
else:
target.add(head)
head = head.next
return False
解法2.快慢指针法
思路:两个指针同时移动,一块一慢,如果链表中有环,则迟早相遇。如果到头都没有相遇,说明链表中没环。
class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
if head == None:
return False
p = head
q = head
while q:
if q.next == None:
return False
else:
p = p.next
q = q.next.next
if p == q:
return True
return False