题解 | #【模板】队列#
【模板】队列
https://www.nowcoder.com/practice/afe812c80ad946f4b292a26dd13ba549
双栈实现
public class TemplateQueue {
public static void main(String[] args) {
QueueDemo t = new QueueDemo();
Scanner scan= new Scanner(System.in);
int val = Integer.parseInt(scan.nextLine());
String[] split;
String next;
for(int i = 0; i < val;i++){
next = scan.nextLine();
split = next.split(" ");
if(split[0].equals("pop")){
t.pop();
}
if (split[0].equals("push")){
t.push(Integer.valueOf(split[1]));
}
if (split[0].equals("front")){
t.front();
}
}
}
}
class QueueDemo{
Stack<Integer> stackA = new Stack<>();
Stack<Integer> stackB = new Stack<>();
public void push(int i){
stackA.push(i);
}
public void pop(){
//栈b不为空
if(stackB.size()!=0){
//弹出栈顶元素即可
System.out.println(stackB.pop());
return;
}
//说明栈B为空 栈A不为空
if(stackA.size()!=0){
while (stackA.size()!=0){
stackB.push(stackA.pop());
}
System.out.println(stackB.pop());
return;
}
//栈A 、栈B均为空
System.out.println("error");
}
public void front(){
if(stackB.size()!=0){
System.out.println(stackB.peek());
return;
}
if(stackA.size()!=0){
while (stackA.size()!=0){
stackB.push(stackA.pop());
}
System.out.println(stackB.peek());
return;
}
System.out.println("error");
}


凡岛公司福利 676人发布