我的方法:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def hasCycle(self, head: ListNode) -> bool:
p = head
if p!=None:
dic = {}
dic[p] = not p in dic
while dic[p] == True:
if p.next != None :
p = p.next
dic[p] = not p in dic
else:
return False
return True
else:
return False
小周改写的版本
代码简洁了不少,但是不知道为啥运行速度比我的要慢一点
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def hasCycle(self, head: ListNode) -> bool:
p = head
dic={}
while p!=None:
if p in dic:
return True
else:
dic[p]=1
p=p.next
return
小周的另一种思路
牛逼!!
class Solution:
def hasCycle(self, head: ListNode) -> bool:
p = head#走两步
q = head#走一步
while p!=None:
if p.next==None:
return False
else:
p=p.next.next
q=q.next
if p==q:
return True
return False