题目描述
实现一个队列。
操作:
push x:将 x 加入队尾,保证 x 为 int 型整数。
pop:输出队首,并让队首出队
front:输出队首:队首不出队
思路
在本题中,我们使用一个ArrayList来实现一个数组,建立一个指向数组头部的指针,对于push操作,我们使用add方法加入队列即可;对于pop操作,我们要判断当前队列是否为空,如果为空则不能pop出元素,返回“error”,但是当前判断数组为空的操作就是:判断头部指针的位置是否与数组长度一致,如果队列有两个元素,pop1次指针+1,待pop执行两次后,头部指针index=size=2,就判断数组为空,返回“error”,其实前面两个元素依旧存在,只是由于index增加就认为前面元素被弹出队列,实际它还是存在的,简而言之,判断数组为空的条件就是认为pop的次数等于数组中截止目前一共add元素的个数;front就访问最近pop后的下一个元素即可。想清楚之后这道题其实也没啥难度。
输入描述
第一行为一个正整数 n ,代表操作次数。(1≤n≤100000)
接下来的 n,每行为一个字符串,代表一个操作。保证操作是题目描述中三种中的一种。
输出描述
如果操作为push,则不输出任何东西。
如果为另外两种,若队列为空,则输出 "error“
否则按对应操作输出。
示例
代码
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
//int n = Integer.valueOf(scan.nextLine().trim());//转为包装类型Integer,并且去除空格
int n = Integer.parseInt(scan.nextLine());
for (int i = 0; i < n; i++) {
String[] operator = scan.nextLine().split(" ");
if ("push".equals(operator[0])) {
push(operator[1]);
} else if ("pop".equals(operator[0])) {
System.out.println(pop());
} else {
System.out.println(front());
}
}
}
public static ArrayList<String> arr = new ArrayList<>();
public static int index = 0;
public static void push(String num) {
arr.add(num);
}
public static String pop() {
return index == arr.size() ? "error" : arr.get(index++);
}
public static String front() {
return index == arr.size() ? "error" : arr.get(index);
}
}