本文共 943 字,大约阅读时间需要 3 分钟。
思路:
两个栈。当有输出的时候。如果B里有东西就pop.没有的话把所有A里面的东西拿出来放入B。所有的入队全部放在A里面。import java.util.Stack;class MyQueue { // Push element x to the back of queue. StackstackA=new Stack (); Stack stackB=new Stack (); boolean isOut=true; public void push(int x) { stackA.push(x); } // Removes the element from in front of queue. public void pop() { if(stackB.isEmpty()) { while(!stackA.isEmpty()) { stackB.push(stackA.pop()); } } stackB.pop(); } // Get the front element. public int peek() { if(stackB.isEmpty()) { while(!stackA.isEmpty()) { stackB.push(stackA.pop()); } } return stackB.peek(); } // Return whether the queue is empty. public boolean empty() { return stackA.isEmpty()&&stackB.isEmpty(); }}
转载地址:http://ybuvb.baihongyu.com/