Question:
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 must the only standard operations of a queue – which means only
push to back
,, peek/pop from front
size
, and is empty
operations is Valid.
- Depending on your language, queue May is not supported natively. You could simulate a queue by using a list or deque (double-ended queue), as long as if you have standard operations of a Q Ueue.
- You may assume this all operations is valid (for example, no pop or top operations would be called on an empty stack).
Thoughts:
One simple solution is Using the queues to build a stack, we initiate the queues which be Q1 and Q2 (Q2 is a temprory queu e), every time the "Stack" is on-to-push, we add all the elements in Q1 to Q2, and push the new element into Q1 to make Sure the new element comes out the first.
However, there ' s one method that can build this stack class with only one Queue with O (n) time, the whole point was to Rema In the queue as it was, but every time we perform POPs () and Top () function, we remove all of the elements in the queue Except the very last one in the bottom originally, and push all these removed elements back to it's own Queue after the "O Riginal Bottom "element, in this, We keep the Queue structure as it's and we fetch the bottom element in the Queue, which help us to perform the Pop () ADN Top () function.
Code:
Class Mystack { //Push element x onto stack. queue<integer> q = new linkedlist<integer> (); public void push (int x) { q.add (x); } Removes the element on top of the stack. public void Pop () { if (!q.isempty ()) { int length = Q.size (); for (int i = 1; i<length; i++) { q.add (Q.remove ()); } Q.remove (); } else return; } Get the top element. public int Top () { if (!q.isempty ()) { int size = Q.size (); for (int i = 1; i < size; i++) Q.add (Q.remove ()); int ret = Q.remove (); Q.add (ret); return ret; } else return-1; } Return whether the stack is empty. public Boolean empty () { return q.isempty (); }}
Implementing Stack Using Queue