Original title URL: https://leetcode.com/problems/implement-stack-using-queues/
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 use 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). Idea: When the stack is pressed, a temporary queue is used to store the elements of the last stack (so that the team is first out), then the contents of the previous queue are added to the temporary queue, and then the temporary queue is overwritten back to the queue that holds the stack data, and the order is reversed.
Source:
Class Mystack {
private queue<integer> Queue = new linkedlist<integer> ();
Private queue<integer> buf = new linkedlist<integer> ();
Push element x onto stack.
public void push (int x) {
buf.add (x);
while (!queue.isempty ()) Buf.add (Queue.remove ());
queue<integer> temp = queue;
queue = BUF;
BUF = temp;
}
Removes the element on top of the stack.
public void Pop () {
queue.remove ();
}
Get the top element.
public int Top () {
return Queue.peek ();
}
Return whether the stack is empty.
public Boolean empty () {
return queue.isempty ();
}
}
Time complexity: Stack o (n), stack, view stack top is O (1), Space complexity is O (n)