Implement a MyQueue class which implements a queue using two stacks.
/*Use two stacks, when enqueue, first pop all the elements in stack2 on stack1, then push the element on stack1. when dequeue, first pop all elements in stack1 to stack2, then pop an element. Notice that the order of elements in two stacks are opposite. */ import java.util.*; public class MyQueue { Stack<Integer> stack1 = new Stack<Integer>(); Stack<Integer> stack2 = new Stack<Integer>(); public void enqueue(int key) { while(stack2.isEmpty() == false) { stack1.add(stack2.pop()); } stack1.add(key); } public int dequeue() { while(stack1.isEmpty() == false) { stack2.add(stack1.pop()); } return stack2.pop(); } public static void main(String[] args) { MyQueue mq = new MyQueue(); mq.enqueue(1); mq.enqueue(2); System.out.println(mq.dequeue()); mq.enqueue(3); System.out.println(mq.dequeue()); System.out.println(mq.dequeue()); } }
原文:http://www.cnblogs.com/pyemma/p/3836570.html