任务描述
给定一个链表,判断链表中是否有环。 为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。思路
双指针实现代码
# 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 head.next == None: return False l1 = l2 = head while l2 != None and l1 != None : if l1.next != None and l2.next != None and l2.next.next != None: l1 = l1.next l2 = l2.next.next else: return False if l1 == l2: return True return False