Implement the following operations of a stack using queues. Push (x)--push element x onto stack. Pop ()--Removes the element on top of the stack. Top ()-Get the top element. Empty ()--return whether the stack is empty. Notes:
You are must use only standard operations of a queue--which means only push to back, peek/pop from front, size, and are empty Operations are valid. Depending on your language, the queue may isn't be supported natively. You could simulate a queue by using a list or deque (double-ended queue) as long as your use only standard operations of a Q Ueue. You may assume this all operations are valid (for example, no POPs or top operations would be called on a empty stack).
The main idea: the use of queues to achieve the stack of push, pop, top and empty operations.
Solution: Each push operation, the element is placed at the head of the team, the other elements in order to move to the end of the team. The other operations are basically consistent with the queue operations in C++stl.
The code is as follows:
Class Mystack {public
:
/** Initialize your data structure here. */
Mystack () {While
(Que.size ()) Que.pop ();
}
/** Push element x onto stack. */
void push (int x) {
que.push (x);
int sz = Que.size ();
while (Sz > 1) {
Que.push (Que.front ());
Que.pop ();
sz--
}
}
/** removes the element on top of the stack and returns that element. */
int pop () {
int tmp = Que.front ();
Que.pop ();
return tmp;
}
/** get the top element. */
int Top () {return
que.front ();
}
/** Returns Whether the stack is empty. * *
bool Empty () {return
que.empty ();
}
Private:
queue<int> que;