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:
- Must use onlyStandard operations of a queue – which means only
push to back
,peek/pop from front
,size
, andis 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).
Update (2015-06-11):
The class name of the Java function had been updated to Mystack instead of Stack.
Thought analysis: This problem and Leetcode Implement queue using stacks similar, the idea is similar, with two queues to simulate a stack. In particular, the stack only needs to be placed at the tail of the Q1 queue. Out of the stack, Q1 all elements except the last element out of the queue, and presses into the tail of the Q2 queue, then takes the last element out of the Q1. Note To ensure that Q2 is empty, it is a secondary queue, so we exchange Q1 and Q2. The top and Pop methods are similar, except that the last element in the Q1 is removed and then pressed into the Q2 to ensure that the element is not lost because we just want to see the top element of the stack and do not want to actually stack it.
AC Code
Class Mystack { //queue linkedlist<integer> q1 = new linkedlist<integer> (); linkedlist<integer> q2 = new linkedlist<integer> (); Push element x onto stack. public void push (int x) { q1.add (x); } Removes the element on top of the stack. public void Pop () { //peek (); poll (); while (Q1.size () > 1) { Q2.add (Q1.poll ()); } Q1.poll (); Switch linkedlist<integer> tem = Q1; q1 = Q2; q2 = tem; } Get the top element. public int Top () { //peek (); poll (); while (Q1.size () > 1) {q2.add (Q1.poll ()); } int res = Q1.peek (); Q2.add (Q1.poll ()); Switch linkedlist<integer> tem = Q1; q1 = Q2; q2 = TEM; return res; } Return whether the stack is empty. public Boolean empty () { return q1.isempty (); }}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Leetcode Implement Stack using Queues