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 element x to the back of the queue.
- int pop() Removes the element from the front of the queue and returns it.
- int peek() Returns the element at the front of the queue.
- boolean empty() Returns true if the queue is empty, false otherwise.
Notes:
- You must use only standard operations of a stack, which means only push to top, peek/pop from top, size, and is empty operations are valid.
- Depending on your language, the stack may not be supported natively. You may simulate a stack using a list or deque (double-ended queue) as long as you use only a stack's standard operations.
제한 사항
- 1 <= x <= 9
- At most 100 calls will be made to push, pop, peek, and empty.
- All the calls to pop and peek are valid.
입출력 예
Example 1:
Input ["MyQueue", "push", "push", "peek", "pop", "empty"] [[], [1], [2], [], [], []] Output [null, null, null, 1, 1, false] Explanation MyQueue myQueue = new MyQueue(); myQueue.push(1); // queue is: [1] myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue) myQueue.peek(); // return 1 myQueue.pop(); // return 1, queue is [2] myQueue.empty(); // return false
Python 코드
Python code
class MyQueue: def __init__(self): // 문제에서 2개의 스택을 사용하라고 하니, 배열을 2개를 사용 self.stack1 = [] self.stack2 = [] def push(self, x: int): // stack1에는 push 데이터를 넣어줌 self.stack1.append(x) def pop(self): // pop을 할때에는 stack1의 배열을 거꾸로 변경하는 과정이 필요 // pop을 할때, stack1.pop()을 하여, stack2에 넣어줌 // stack1 [1, 2, 3] -> stack2 = [3, 2, 1] self.peek() return self.stack2.pop() def peek(self): // peek는 큐의 첫번째 값을 가져와야 하므로 // stack1의 모든 값을 거꾸로 stack2에 넣어서, stack2[-1]을 리턴 if not self.stack2: // stack1의 모든 값이 나올때까지 해주는데, // stack2가 비어있지 않은 경우에 stack2에 값을 넣을 경우 // pop()이 힘들어지니 stack1을 그대로 이용 // 1) stack1 [1, 2, 3] -> stack2 [3, 2, 1] // 2) MyQueue.push(4) // 3) stack1 -> [4] , stack2 [3, 2, 1] 의 경우 // stack1의 값을 넣어주면 stack2는, [3, 2, 1, 4]가 되므로 pop을 하기가 힘듬 // 4) stack1의 [4]는 어차피 stack2가 다 빌때까지 필요없으므로 // 그냥 stack2가 빌때까지 stack1에 넣어둠 while self.stack1: self.stack2.append(self.stack1.pop()) return self.stack2[-1] def empty(self): return (len(self.stack1) == 0) and (len(self.stack2) == 0)
* 참고 링크 : https://jasmine46.tistory.com/71
C++ 코드
C ++ code
// Time: O(1), amortized // Space: O(n) class Queue { public: // Push element x to the back of queue. void push(int x) { A_.emplace(x); } // Removes the element from in front of queue. void pop(void) { peek(); B_.pop(); } // Get the front element. int peek(void) { if (B_.empty()) { // Transfers the elements in A_ to B_. while (!A_.empty()) { B_.emplace(A_.top()); A_.pop(); } } if (B_.empty()) { // B_ is still empty! throw length_error("empty queue"); } return B_.top(); } // Return whether the queue is empty. bool empty(void) { return A_.empty() && B_.empty(); } private: stack<int> A_, B_; };
* 참고 링크 : https://shareablecode.com/snippets/implement-queue-using-stacks-c-solution-leetcode-FaBa-R43B
출처
'코딩테스트 > Leet Code' 카테고리의 다른 글
[Leet Code] 342_Power of Four (0) | 2022.02.11 |
---|---|
[Leet Code] 622. Design Circular Queue (0) | 2022.01.21 |
[Leet Code] 225. Implement Stack using Queues (0) | 2022.01.21 |
[Leet Code] 150. Evaluate Reverse Polish Notation (0) | 2022.01.21 |
[Leet Code] 43. Multiply Strings (0) | 2022.01.14 |