题解 | #【模板】循环队列#
【模板】循环队列
http://www.nowcoder.com/practice/0a3a216e50004d8bb5da43ad38bcfcbf
import java.util.*;
public class Main {
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
solve01();
}
/*
3 10
push 1
push 2
front
push 3
push 4
pop
pop
pop
front
pop
1
full
1
2
3
empty
empty
*/
/*
10 48
front
front
pop
push 6
front
push -3
push 14
pop
front
front
pop
front
pop
front
push -16
pop
pop
pop
push -9
front
front
front
push 11
front
pop
push 3
front
push 0
pop
pop
pop
push 0
push 4
push -15
push 9
front
pop
pop
front
pop
front
push -3
front
pop
front
front
front
pop
empty
empty
empty
6
6
-3
-3
-3
14
14
empty
-16
empty
empty
-9
-9
-9
-9
-9
11
11
3
0
0
0
4
-15
-15
9
9
9
-3
-3
-3
-3
*/
static void solve01() {
int n = sc.nextInt(), q = sc.nextInt();
sc.nextLine();
CirQueue queue = new CirQueue(n);
while (q-- > 0) {
String arr[] = sc.nextLine().split(" ");
if (arr[0].equals("push")) {
boolean flag = queue.push(Integer.parseInt(arr[1]));
if (!flag) System.out.println("full");
} else if (arr[0].equals("pop")) {
Integer pop = (Integer) queue.pop();
if (pop == null) {
System.out.println("empty");
} else {
System.out.println(pop);
}
} else if (arr[0].equals("front")) {
Integer top = (Integer) queue.front();
if (top == null) {
System.out.println("empty");
} else {
System.out.println(top);
}
}
}
}
}
/**
* 循环队列
*/
class CirQueue {
private int queueSize;
private int front;
private int rear;
private Object queueList[];
public CirQueue(int queueSize) {
this.queueSize = queueSize + 1;
queueList = new Object[this.queueSize];
front = 0;
rear = 0;
}
/**
* 判断队列是否为空
* @return
*/
public boolean isEmpty() {
return rear == front;
}
/**
* 判断队列是否为满
* @return
*/
public boolean isFull() {
return (rear + 1) % queueSize == front;
}
/**
* 获取队列头元素
* @return
*/
public Object front() {
// 如果队列不为空, 返回队头元素, 否则返回 null
return isEmpty() ? null : queueList[front];
}
/**
* 出队
* @return
*/
public Object pop() {
if (isEmpty()) return null;
Object ele = queueList[front];
front = (front + 1) % queueSize;
return ele;
}
/**
* 入队
* 如果队列未满, 添加元素到队尾, 否则提示队列已满
* @param ele
* @return
*/
public boolean push(Object ele) {
if (isFull()) return false;
queueList[rear] = ele;
rear = (rear + 1) % queueSize;
return true;
}
}