- Topic
- 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.
- Ideas:
- One stack is pressed into the element, and the other stack acts as a buffer, and the stack 1 element is pushed back into the stack 2.
- Code
Import java.util.stack;/** * Two stacks implementation of a queue * @author MSI */public class requeue{ stack<integer> sk1=new stack< Integer> (); Stack<integer> sk2=new stack<integer> (); public void push (int val) { Sk1.push (val); } public int pop () throws exception{//stacks 1 sequentially and presses into the stack 2 if (Sk1.isempty () &&sk2==null) { throw new Exception ( "Queue is empty"); while (Sk2.isempty ()) { while (!sk1.isempty ()) { Sk2.push (Sk1.pop ()); } } return Sk2.pop (); } public static void Main (String args[]) throws exception{ requeue q1=new requeue (); Q1.push (1); Q1.push (2); Q1.push (3); while (q1!=null) System.out.println (Q1.pop ()); } }
Interview 9-use two stacks to implement a queue, complete push and pop operations for the queue