题解 | #【模板】队列#
【模板】队列
http://www.nowcoder.com/practice/afe812c80ad946f4b292a26dd13ba549
import java.util.*;
import java.util.Scanner;
public class Main{
static Queue<Integer> q = new LinkedList<Integer>();
static int[] values = null;
static int size = 0;
static int head = 0;
static int lenth = 0;
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
while(sc.hasNextLine()){
//拆分输入
String input = sc.nextLine();
String[] inputs = input.split(" ");
String op = inputs[0];
//如果数据长度为1
if(inputs.length > 1){
//插入操作
int val = Integer.parseInt(inputs[1]);
push(val);
}else{
//输出或者出队列操作
if("pop".equals(op)) pop();
else if("front".equals(op)) front();
else {
lenth = Integer.parseInt(op);
values = new int[lenth];
}
}
}
}
public static void push(int itme){
//q.add(itme);
//考虑重置数组
if(head + size == lenth){
reset();
}else{
values[head + size] = itme;
}
size++;
}
public static void pop(){
//if(q.isEmpty()) System.out.println("error");else System.out.println(q.poll());
if(size == 0){
System.out.println("error");
}else{
System.out.println(values[head]) ;
head++;
size--;
}
}
public static void front(){
if(size == 0){
System.out.println("error");
}else{
System.out.println(values[head]) ;
}
//if(q.isEmpty()) System.out.println("error");else System.out.println(q.peek());
}
//不需要扩容,需要重置一下
public static void reset(){
//从head开始,遍历size
for(int i = 0;i < size;i++){
values[i] = values[head+i];
}
head = 0;
}
}