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.
- You must use only standard operations of a stack -- which means only
push to top
,peek/pop from top
,size
, andis 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).
class Queue {
public:
stack<int> A, B;
void push(int x) {
A.push(x);
}
void pop(void) {
while(!A.empty()) {
B.push(A.top());
A.pop();
}
B.pop();
while(!B.empty()) {
A.push(B.top());
B.pop();
}
}
int peek(void) {
if( !A.empty() ) {
while(!A.empty()) {
B.push(A.top());
A.pop();
}
int p = B.top();
while(!B.empty()) {
A.push(B.top());
B.pop();
}
return p;
}
return 0;
}
bool empty(void) {
return A.empty();
}
};
int main() {
Queue queue;
queue.push(1);
queue.push(2);
queue.push(3);
while(!queue.empty()) {
cout << queue.peek();
queue.pop();
}
//queue.pop();
cout << queue.peek() << endl;
if(queue.empty() == true)
cout << "empty" << endl;
else
cout << "not empty" << endl;
return 0;
}