题目要求:
用两个栈实现队列,支持队列的基本操作
CODE
import java.util.*;
public class Main{
public static void main(String[] args){
QueueByStack sq = new QueueByStack();
Scanner scanner = new Scanner(System.in);
int N = Integer.valueOf(scanner.nextLine());
for(int i=0;i<N;i++){
String line = scanner.nextLine();
if(line.startsWith("add")){
String[] num = line.split(" ");
int x =Integer.valueOf(num[1]);
sq.add(x);
}else if(line.startsWith("poll")){
sq.poll();
}
else if(line.startsWith("peek")){
int res = sq.peek();
System.out.println(res);
}
}
}
}
class QueueByStack{
public Stack<Integer> s1;
public Stack<Integer> s2;
public QueueByStack(){
this.s1 = new Stack<Integer>();
this.s2 = new Stack<Integer>();
}
public void add(int x){
s1.push(x);
}
public Integer poll(){
if(!s2.isEmpty()){
return s2.pop();
}else{
while(!s1.isEmpty()){
s2.push(s1.pop());
}
return s2.pop();
}
}
public Integer peek(){
if(!s2.isEmpty()){
return s2.peek();
}else{
while(!s1.isEmpty()){
s2.push(s1.pop());
}
return s2.peek();
}
}
}
KEYPOIT
用2个栈,S1和S2
- 加:往S1里加
- poll:
-
- 如果S2不为空,直接操作S2,因为S2都是老的;
-
- 如果S2为空,则得把S1的元素整S2里,这样从S2出正好是队列的出了
- peek:同S2
!!!Stack是pop(), Queue是poll()