由两个栈组成队列

来源:互联网 发布:淘宝正品哥弟女裤 编辑:程序博客网 时间:2024/04/30 11:09
/*
 * question:编写一个类,用两个栈实现队列,支持队列的基本操作(add、poll、peek)
 * time:2017/4/1
 * name:lqs
 */
package stack1;
/*
 *stackPush:压入栈
 *stackPop:弹出栈
 */
import java.util.*;
public class TwoStacksChangeToQueue {
private static Stack<Integer>stackPush;
private static Stack<Integer>stackPop;

public  TwoStacksChangeToQueue(){//构造函数
stackPush=new Stack<Integer>();
stackPop=new Stack<Integer>();
}
public static void add(int pushNumber){//加元素
stackPush.push(pushNumber);//压入stackPsuh栈
}
public static int poll(){//出栈
if(stackPush.empty()&&stackPop.empty()){
throw new RuntimeException("Queue is empty!");
}
else if(stackPop.isEmpty()){
while(!stackPush.empty()){
stackPop.push(stackPush.pop());//获取stackpush栈顶元素,依次倒入stackPop栈
}
}
return stackPop.pop();//返回stackPop栈的出栈元素
}
public static int peek(){//取栈顶元素
if(stackPop.empty()&&stackPush.empty()){
throw new RuntimeException("Queue is empty!");
}
else if(stackPop.empty()){
while(!stackPush.empty()){
stackPop.push(stackPush.pop());
}
}
return stackPop.peek();//返回stackPop栈顶元素

}
public static void main(String[] args) {
TwoStacksChangeToQueue TSCTQ=new TwoStacksChangeToQueue();//实例化类对象
int test[]={1,2,3,4,5,6,7,8,9};//测试数组
int pushNumber[]=new int[test.length];//用数组记录入栈的元素
for(int i=0;i<test.length;i++){
TSCTQ.add(test[i]);
pushNumber[i]=stackPush.peek();
System.out.println("第"+i+"入栈的元素为:"+pushNumber[i]);
}
int peekNumber1=TSCTQ.peek();//获取栈顶元素
int []popNumber=new int[test.length];//用数组存放出栈的元素
System.out.println();
System.out.println("当前栈顶元素为:"+peekNumber1);
System.out.println();
for(int i=0;i<test.length-1;i++){
popNumber[i]=TSCTQ.poll();
System.out.println("出栈元素为:"+popNumber[i]);
}
int peekNumber2=TSCTQ.peek();
System.out.println();
System.out.println("当前栈顶元素为:"+peekNumber2);
}
}
1 0
原创粉丝点击