Title Description
Implement a queue with two stacks to complete the push and pop operations of the queue. The elements in the queue are of type int.
650) this.width=650; "src=" Http://s4.51cto.com/wyfs02/M02/78/0D/wKiom1Z08FiDnl5lAAAnWJmSuig058.png "title=" Untitled. png "alt=" Wkiom1z08fidnl5laaanwjmsuig058.png "/>
The nature of the queue is FIFO first.
, the push operation puts the element into Stack1, the pop operation first takes the element out, presses into the Stack2 and then launches the stack top element from the Stack2. When the Stack2 is not empty, first do not take out stack1 deposit Stack2 operation, but directly from the Stack2 to remove the top element.
Import java.util.stack;public class solution { static stack <Integer> stack1 = new Stack<Integer> (); static Stack<integer> stack2 = new stack<integer> (); static public static void push (Int node) { stack1.push (node); } public static int pop () { if (Stack2.empty ()) { while (!stack1.empty ()) { &nBsp; stack2.push (Stack1.pop ()); } } Int n=stack2.pop (); return n; } public static void main (String[] args) { push (1); push (2); push (3); &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;PR (pop ()); &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;PR ( Pop ()); pr (pop ()); push (5); pr (pop ()); push (4); &nbsP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;PR (pop ()); public &NBSP;STATIC&NBSP;VOID&NBSP;PR (Int a) { system.out.println (a); } } }
Using two stacks to implement a queue