用数组结构实现大小固定的队列和栈
实现队列
通过一个size成员变量来记录队列的大小,避免复杂的公式
public class MyQueue {
private int[] nums;
private int size = 0;//队列大小
private int head = 0;//队头
private int end = 0;//队尾
public MyQueue(int size) {
nums = new int[size];
}
/**
* 入队操作
* @param num
*/
public void enQueue(int num) {
if (size == nums.length) {
throw new ArrayIndexOutOfBoundsException("the queue is full");
}
nums[end] = num;
end = ++end == nums.length ? 0 : end;
size++;
}
/**
* 出队操作
* @return
*/
public int deQueue() {
if (size == 0) {
throw new ArrayIndexOutOfBoundsException("the queue is empty");
}
int tmp = nums[head];
head = ++head == nums.length ? 0 : head;
size--;
return tmp;
}
}
实现栈
public class MyStack {
private int[] nums;
private int size = 0;//栈的大小
private int top = -1;//栈顶位置
public MyStack(int size) {
nums = new int[size];
}
/**
* 入栈操作
* @param num
*/
public void push(int num) {
if (size == nums.length) {
throw new ArrayIndexOutOfBoundsException("your stack is full");
}
nums[++top] = num;
size++;
}
/**
* 出栈操作
* @return
*/
public int pop() {
if (size == 0) {
throw new ArrayIndexOutOfBoundsException("your stack is empty");
}
int tmp = nums[top];
top--;
size--;
return tmp;
}
}