0
点赞
收藏
分享

微信扫一扫

程序员代码面试指南第二版 2.由两个栈组成的队列


​​welcome to my blog​​

程序员代码面试指南第二版 2.由两个栈组成的队列

题目描述

用两个栈实现队列,支持队列的基本操作。
输入描述:
第一行输入一个整数N,表示对队列进行的操作总数。

下面N行每行输入一个字符串S,表示操作的种类。

如果S为"add",则后面还有一个整数X表示向队列尾部加入整数X。

如果S为"poll",则表示弹出队列头部操作。

如果S为"peek",则表示询问当前队列中头部元素是多少。
输出描述:
对于每一个为"peek"的操作,输出一行表示当前队列中头部元素是多少。

示例1

输入
6
add 1
add 2
add 3
peek
poll
peek

输出
1
2

第一次做; 要注意sc.nextLine()和 sc.nextInt()差别, nextLine()不会读入换行符, sc.nextInt()会有读入换行符

import java.util.Scanner;
import java.util.Stack;

public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int n = Integer.valueOf(sc.nextLine());
String str;
myQueue q = new myQueue();
for(int i=0; i<n; i++){
str = sc.nextLine();
if(str.startsWith("add"))
q.add(Integer.valueOf(str.split(" ")[1]));
if(str.startsWith("poll"))
q.poll();
if(str.startsWith("peek"))
System.out.println(q.peek());
}
}
public static class myQueue{
Stack<Integer> s1 = new Stack<>();
Stack<Integer> s2 = new Stack<>();
public void add(int a){
s1.push(a);
}
public void poll(){
if(s2.isEmpty())
while(!s1.isEmpty())
s2.push(s1.pop());
s2.pop();
}
public int peek(){
if(s2.isEmpty()){
while(!s1.isEmpty())
s2.push(s1.pop());
}
return s2.peek();
}
}
}


举报

相关推荐

两个栈组成队列

0 条评论