package StackAndQueue; import java.util.Stack; /** * Use two stacks to implement a queue, complete the queue Push and Pop operations. Elements in the queue are of type int. * : * Stack A is used to queue in, stack B is used to queue out * When stack B is empty, Public static void main(String[] args) {Solution18 Solution18 = new Solution18(); solution18.push(1); solution18.push(2); System.out.println(solution18.pop()); solution18.pop(); } Stack<Integer> stack1 = new Stack<Integer>(); Stack<Integer> stack2 = new Stack<Integer>(); public void push(int node) { stack1.push(node); } public int pop() {if (stack1.empty() &&stack2.empty ()) {throw new RuntimeException(" queue is empty "); } if (stack2.empty()) { while (! stack1.empty()) { stack2.push(stack1.pop()); } } return stack2.pop(); //stcak2 is responsible for queue exit}}
Copy the code
Wu Peixuan
www.cnblogs.com/wupeixuan/