Leetcode 1670. Design Front Middle Back Queue [Python]

虽然可AC,不过慢。。双向链表可以解决。pop middle得从root的prev方向入手,方可以找到leftmost middle。


class Dnode:
    def __init__(self, val):
        self.val = val
        self.prev = self
        self.next = self


class FrontMiddleBackQueue:

    def __init__(self):
        self.root = Dnode(-1)
        self.size = 0

    def pushFront(self, val: int) -> None:
        root = self.root
        newnode = Dnode(val)
        root.next.prev = newnode
        newnode.prev = root
        newnode.next = root.next
        root.next = newnode
        self.size += 1

    def pushMiddle(self, val: int) -> None:
        newnode = Dnode(val)
        step = 0
        root = self.root
        while step != self.size//2:
            root = root.next
            step += 1
        root.next.prev = newnode
        newnode.prev = root
        newnode.next = root.next
        root.next = newnode
        self.size += 1
        
    def pushBack(self, val: int) -> None:
        root = self.root
        newnode = Dnode(val)
        root.prev.next = newnode
        newnode.prev = root.prev
        root.prev = newnode
        newnode.next = root
        self.size += 1
        
    def popFront(self) -> int:
        root = self.root
        if self.size == 0:return -1
        node = root.next
        root.next.next.prev = root
        root.next = node.next 
        node.prev = None
        node.next = None
        self.size -= 1
        return node.val
        

    def popMiddle(self) -> int:
        root = self.root
        if self.size == 0:return -1
        step = 0
        while step != self.size//2:
            root = root.prev
            step += 1
        node = root.prev
        root.prev.prev.next = root
        root.prev = node.prev 
        node.prev = None
        node.next = None
        self.size -= 1
        return node.val
        

    def popBack(self) -> int:
        root = self.root
        if self.size == 0:return -1
        node = root.prev
        root.prev.prev.next = root
        root.prev = node.prev 
        node.prev = None
        node.next = None
        self.size -= 1
        return node.val
        


# Your FrontMiddleBackQueue object will be instantiated and called as such:
# obj = FrontMiddleBackQueue()
# obj.pushFront(val)
# obj.pushMiddle(val)
# obj.pushBack(val)
# param_4 = obj.popFront()
# param_5 = obj.popMiddle()
# param_6 = obj.popBack()

 

你可能感兴趣的:(Leetcode学习记录)