leetcode-python-环形列表

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

 

posted @ 2021-06-03 15:44  泊鸽  阅读(182)  评论(0)    收藏  举报