早上写了一下利用两个栈来实现一个队列的题目,代码如下,请大家写一下自己的代码!谢谢了。
package stackqueue;
import java.util.Stack;
public class TwoStackToQueue<T> {
private Stack<T> stackone;
private Stack<T> stacktwo;
public TwoStackToQueue(){
stackone = new Stack();
stacktwo = new Stack();
}
public void add(T elem){
stackone.add(elem);
}
public void display(){
int length = stackone.size()-1;
if(length<0 || stackone == null){
return;
}
while(length>0){
stacktwo.push(stacktwo.pop());
length--;
}
}
public void enQueue(T elem){
if(stacktwo.size()>0){
while(stacktwo.size() > 0){
stackone.push(stacktwo.pop());
}
}
stackone.push(elem);
}
public T deQueue(){
if(stackone.size() == 0){
return null;
}
while(stackone.size()>0){
stacktwo.push(stackone.pop());
}
return stacktwo.pop();
}
public static void main(String[]args){
TwoStackToQueue <Integer>twoStackQueue = new TwoStackToQueue<Integer>();
twoStackQueue.enQueue(new Integer(2));
twoStackQueue.enQueue(new Integer(4));
System.out.println(twoStackQueue.deQueue());
}
}