环形链表
题目
给定一个链表,判断链表中是否有环。
链接:https://leetcode-cn.com/problems/linked-list-cycle/
思路
通过快慢指针实现,while循环条件为p1 != p2(设p1为慢指针,p2为快指针),在循环内进行判断,如果快指针p2或p2.next为None,则说明没有环,return False,若跳出循环,则说明有环,return True。
Python代码
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def hasCycle(self, head: ListNode) -> bool:
if head == None:
return False
p1 = head
p2 = head.next
while p1 != p2:
if p2 == None or p2.next == None:
return False
p1 = p1.next
p2 = p2.next.next
return True
相关知识点
快慢指针方法的理解
执行结果
执行用时 : 52 ms, 在所有 Python3 提交中击败了78.76% 的用户
内存消耗 : 16.6 MB, 在所有 Python3 提交中击败了5.22%的用户