Implement the following operations of a queue using stacks.
- push(x) -- Push element x to the back of queue.
- pop() -- Removes the element from in front of queue.
- peek() -- Get the front element.
- empty() -- Return whether the queue is empty.
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, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack.
- You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).
1 class Queue {
2 stack<int> s1;
3 stack<int> s2;
4 public:
5 // Push element x to the back of queue.
6 void push(int x) {
7 while(!s1.empty()){
8 s2.push(s1.top());
9 s1.pop();
10 }
11 s1.push(x);
12 while(!s2.empty()){
13 s1.push(s2.top());
14 s2.pop();
15 }
16 }
17
18 // Removes the element from in front of queue.
19 void pop(void) {
20 s1.pop();
21 }
22
23 // Get the front element.
24 int peek(void) {
25 return s1.top();
26 }
27
28 // Return whether the queue is empty.
29 bool empty(void) {
30 return s1.empty();
31 }
32 };