队列
约定:
front 指向队头前一位置
rear 指向队尾
从-1出发
队列长度未maxSize
public class Queue {
int[]a;
int maxSize;
int front;
int rear;
public static void main(String[] args) {
Queue queue = new Queue(3);
queue.add(1);
queue.add(2);
queue.add(3);
queue.showAll();
}
public void showAll() {
if (isEmpty()) {
System.out.println("队列为空无法打印");
}
for (int i = front + 1; i <= rear; i++) {
System.out.print(a[i] + " ");
}
}
public int size() {
return maxSize;
}
public void add(int data) {
if (isFull()) {
throw new RuntimeException("队列已满");
}
a[++rear] = data;
}
public int del()
{
if (isEmpty()) {
throw new RuntimeException("队列为空");
}
return a[++front];
}
public boolean isFull() {
return rear == maxSize - 1;
}
public boolean isEmpty() {
return rear == front;
}
public Queue(int maxSize)
{
this.maxSize = maxSize;
this.front = -1;
this.rear = -1;
a = new int[maxSize];
}
}
循环队列
约定:
front 指向队头
rear 指向队尾后一位
从0开始
package test;
//rear 指向队尾后一位置
//front 指向队头
public class CircleQueue {
int[] a;
int front;
int rear;
int maxSize;
public static void main(String[] args) {
CircleQueue circleQueue = new CircleQueue(3);
circleQueue.add(1);
circleQueue.add(3);
circleQueue.showAll();
}
public CircleQueue(int maxSize) {
this.maxSize = maxSize;
this.front = 0;
this.rear = 0;
a = new int[maxSize];
}
public boolean isFull() {
return (rear + 1) % maxSize == front;
}
public boolean isEmpty()
{
return rear == front;
}
public void add(int data) {
if (isFull()) {
throw new RuntimeException("队列已满");
}
a[rear] = data;
rear = (rear + 1) % maxSize;
}
public int del() {
if (isEmpty()) {
throw new RuntimeException("队列为空");
}
int value = a[front];
front = (front + 1) % maxSize;
return value;
}
public int size() {
return (rear + maxSize - front) % maxSize;
}
public void showAll() {
if (isEmpty()) {
throw new RuntimeException("队列为空无法打印");
}
for (int i = front; i < front + size(); i++) {
System.out.print(a[i] + " ");
}
}
}