LeetCodeEasy- [Interview Question 09. Implementing Queue with Two Stacks]

Implement a queue with two stacks. The declaration of the queue is as follows. Please implement its two functions appendTail and deleteHead to complete the functions of inserting integers at the end of the queue and deleting integers at the head of the queue. (If there are no elements in the queue, the deleteHead operation returns -1)

Example 1:

输入:
["CQueue","appendTail","deleteHead","deleteHead"]
[[],[3],[],[]]
输出:[null,null,3,-1]


Example 2:

输入:
["CQueue","deleteHead","appendTail","appendTail","deleteHead","deleteHead"]
[[],[],[5],[2],[],[]]
输出:[null,-1,null,null,5,2]


prompt:

1 <= values ​​<= 10000
up to 10000 calls will be made to appendTail and deleteHead

Source: LeetCode (LeetCode)
link: https://leetcode-cn.com/problems/yong-liang-ge-zhan-shi-xian-dui-lie-lcof
. Please contact the official authorization for commercial reprint, and please indicate the source for non-commercial reprint.

Idea 1: Two stacks: data stack + auxiliary stack

It should be that the order of the stack and the queue is exactly the opposite, then the two stacks are just the same (inverted twice).

class CQueue:

    def __init__(self):
        self.stack1 = [] # 存数
        self.stack2 = [] # 

    def appendTail(self, value: int) -> None:
        while self.stack1 != []:
            self.stack2.append(self.stack1.pop())
        self.stack2.append(value)
        while self.stack2 != []:
            self.stack1.append(self.stack2.pop())
        return None
    def deleteHead(self) -> int:
        if self.stack1 == []:
            return -1
        else:
            return self.stack1.pop()


# Your CQueue object will be instantiated and called as such:
# obj = CQueue()
# obj.appendTail(value)
# param_2 = obj.deleteHead()

Idea 2: Two stacks: data stack + auxiliary stack (improved)

class CQueue:

    def __init__(self):
        self.stack_in = [] 
        self.stack_out = []

    def appendTail(self, value: int) -> None:
        self.stack_in.append(value)

    def deleteHead(self) -> int:
        if not self.stack_out:
            if not self.stack_in:
                return -1
            while self.stack_in:
                self.stack_out.append(self.stack_in.pop())
        return self.stack_out.pop()

 

Published 314 original articles · 22 praises · 20,000+ views

Guess you like

Origin blog.csdn.net/qq_39451578/article/details/105341871