package offer;
import java.util.Stack;
public class Stack_sequence {
private Stack<Integer> stackPush;
private Stack<Integer> stackPop;
public Stack_sequence(){
this.stackPop=new Stack<Integer>();
this.stackPush=new Stack<Integer>();
}
public void add(int newNum){
this.stackPush.push(newNum);
if(this.stackPop.empty()){
while(!this.stackPush.empty()){
this.stackPop.push(this.stackPush.pop());
}
}
}
public int poll(){
if(this.stackPop.empty()&&this.stackPush.empty()){
throw new RuntimeException("Queue is empty!");
}else if(this.stackPop.empty()){
while(!this.stackPush.empty()){
this.stackPop.push(this.stackPush.pop());
}
}
return this.stackPop.pop();
}
public int peek(){
if(this.stackPop.empty()&&this.stackPush.empty()){
throw new RuntimeException("Queue is empty!");
}else if(this.stackPop.empty()){
while(!this.stackPush.empty()){
this.stackPop.push(this.stackPush.pop());
}
}
return this.stackPop.peek();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Stack_sequence q=new Stack_sequence();
q.add(7);
q.add(8);
q.add(90);
System.out.println(q.poll());
System.out.println(q.poll());
}
}
Java: 用两个栈实现队列,支持队列的基本操作(add,poll,peek)
最新推荐文章于 2024-03-22 21:43:29 发布