import java.util.Stack;
public class MyQueue {
public Stack<Integer> s1;
public Stack<Integer> s2;
public MyQueue(Stack<Integer> s1, Stack<Integer> s2) {
this.s1 = s1;
this.s2 = s2;
}
public void add(int value){
s1.push(value);
}
public int poll(){
if(s1.isEmpty() && s2.isEmpty()){
throw new RuntimeException("Queue is empty!");
}else if(s2.isEmpty()){
while(!s1.isEmpty()){
s2.push(s1.pop());
}
}
return s2.pop();
}
public int peek(){
if(s1.isEmpty() && s2.isEmpty()){
throw new RuntimeException("Queue is empty!");
}else if(s2.isEmpty()){
while(!s1.isEmpty()){
s2.push(s1.pop());
}
}
return s2.peek();
}
public static void main(String[] args) {
MyQueue q = new MyQueue(new Stack<Integer>(), new Stack<Integer>());
q.add(1);
q.add(2);
q.add(3);
System.out.println(q.poll());
System.out.println(q.poll());
q.add(4);
System.out.println(q.poll());
System.out.println(q.peek());
}
}
用两个栈实现一个队列
最新推荐文章于 2021-08-01 00:21:31 发布