- 定义队列的实现类
public class ArrayQueue {
private int[] arr;//定义一个数组来模拟实现队列
private int maxSize;//表示队列的最大容量
private int front;//队头
private int end;//队尾
//
public ArrayQueue(int maxSize) {
this.maxSize = maxSize;
arr = new int[maxSize];
front = -1;//初始化时指向队列头部的前一个位置
end = -1;
}
//判断队列是否已满
public boolean isFull() {
return end == maxSize-1;
}
//判断队列是否为空
public boolean isEmpty() {
return end == front;
}
//数据的添加
public void insert(int value) {
if(isFull()) {
System.out.println("队列已满");
return;
} else {
end++;
arr[end] = value;
}
}
//数据的取出
public int remove() {
//判断数据是否为空
if(isEmpty()) {
throw new RuntimeException("队列为空");
}
front++;
return arr[front];
}
}
- 测试类
public class Test {
public static void main(String[] args) {
ArrayQueue a = new ArrayQueue(3);
a.insert(1);//1入队
a.insert(2);//2入队
a.insert(3);//3入队
int b = a.remove();//1出队
int c = a.remove();//2出队
System.out.println(b+"出队");
System.out.println(c+"出队");
}
}
- 输出结果
1出队
2出队
- 定义栈的实现类
public class Stack {
//声明数据,定义栈
private int[] arr;
//定义一个指针来指向数据
private int flag = 0;
//通过构造函数来初始这个栈
public Stack(int maxSize) {
arr = new int[maxSize];
}
//数据的插入
public void push(int value) {
//需要判断栈是否已经满了
if(flag == arr.length) {
System.out.println("已经满了");
return;
}
arr[flag] = value;
flag++;
}
//数据的取出
public int pop() {
//判断栈是否为空
if(flag == 0) {
return -1;
}
int result = arr[flag-1];
flag--;
return result;
}
}
- 测试类
public class Test {
public static void main(String[] args) {
Stack stack = new Stack(3);
stack.push(1);//1入栈
stack.push(2);//2入栈
stack.push(3);//3入栈
int a = stack.pop();
int b = stack.pop();
System.out.println(a+"出栈");
System.out.println(b+"出栈");
}
}
- 输出结果
3出栈
2出栈