首页 > 编程语言 > 详细

leetcode-python-环形列表

时间:2021-06-03 17:17:33      阅读:14      评论:0      收藏:0      [点我收藏+]

1)逐个入栈,检查是否有重复元素出现(效率极低)(类似hashmap)

# 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:
        stack = []
        temp = head
        while temp:
            if temp not in stack:
                stack.append(temp)   
                temp = temp.next
            else:
                return True
        return False

2)双指针,快指针比慢指针多走几步都行,如果相遇则是环形

# 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:
        if head:
            slow = head
            fast = head
            while fast and fast.next:
            
                slow = slow.next
                fast = fast.next.next
                if slow == fast:
                    return True
            return False
        else:
            return False

 

leetcode-python-环形列表

原文:https://www.cnblogs.com/cbachen/p/14845465.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!