python-algorithm

leetcode 232. Implement Queue using Stacks

무적김두칠 2023. 2. 23. 23:31

https://leetcode.com/problems/implement-queue-using-stacks/description/

 

Implement Queue using Stacks - LeetCode

Implement Queue using Stacks - Implement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the functions of a normal queue (push, peek, pop, and empty). Implement the MyQueue class: * void push(int x) Pushes

leetcode.com

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class MyQueue:
 
    def __init__(self):
        self.input = []
        self.output = []
 
    def push(self, x: int-> None:
        self.input.append(x)
        
 
    def pop(self-> int:
        self.peek()
        return self.output.pop()
 
    def peek(self-> int:
        if not self.output:
            while self.input:
                self.output.append(self.input.pop())
        return self.output[-1]
        
 
    def empty(self-> bool:
        return self.input == [] and self.output == []
        
 
 
# Your MyQueue object will be instantiated and called as such:
# obj = MyQueue()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.peek()
# param_4 = obj.empty()
cs
반응형