力扣刷题(python)50天——第三十二天:环形链表
题目
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/linked-list-cycle
方法
想法是模拟链表一直走下去,但问题在于怎么判定进入了循环。
循环链表的标志之一是某个节点有两个不同的节点指向它。
我设置了一个列表来存储链表的每一个节点,每当进入一个新的节点时进行判断是否该节点之前已经出现。
解答
# 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:
return False
list1=[]
list1.append(head)
head=head.next
while head:
if head in list1:
return True
list1.append(head)
head=head.next
return False
执行结果、
额。。。。
提升:
问题与上一题相识,因为我使用了 in 这一关键字。
可以使用字典代替我的列表来做!!!!!!!
哈希表按关键字查询快,数组按序号检索快,链表插入/删除快。
改进:
无意中看见一个比较奇葩的方案:
class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
while head:
if head.val == 'bjfuvth':
return True
else:
head.val = 'bjfuvth'
head = head.next
return False
双指针:
https://leetcode-cn.com/problems/linked-list-cycle/solution/huan-xing-lian-biao-by-leetcode/