由两个栈组成的队列
-
思路
两个栈,一进一出,即可实现队列的先进先出功能。但有三个点需要注意:
1.输入栈中的元素导入输出栈时要将当前输入栈内所有元素丢入输出栈;
2.当输出栈中有元素存在时,不能将输入栈元素导入输出栈;
3.将输入栈元素导入输出栈可以写成一个方法,在队列的add、peek、poll方法中调用即可
具体Java代码如下:
import java.util.*;
public class Main{
private Stack<Integer> s1;
private Stack<Integer> s2;
public Main(){
s1 = new Stack();
s2 = new Stack();
}
public void pushToPop(){
if(s2.isEmpty()){
while(!s1.isEmpty()){
s2.push(s1.pop());
}
}
}
public void add(int number){
s1.push(number);
pushToPop();
}
public int poll(){
if(s1.isEmpty() && s2.isEmpty()){
throw new RuntimeException("QUEUE IS EMPTY");
}
pushToPop();
return s2.pop();
}
public int peek(){
if(s1.isEmpty() && s2.isEmpty()){
throw new RuntimeException("QUEUE IS EMPTY");
}
pushToPop();
return s2.peek();
}
public static void main(String [] arg){
Scanner scanner = new Scanner(System.in);
Main m = new Main();
int n = Integer.valueOf(scanner.nextLine());
String s;
for(int i=0;i<n;i++){
s = scanner.nextLine();
if(s.equals("peek")){
System.out.println(m.peek());
}else if(s.equals("poll")){
m.poll();
}else{
m.add(Integer.valueOf(s.split(" ")[1]));
}
}
}
}
转载自左神程序员代码面试指南