topic requirement:
无
thoughts:
对于用数组结构实现大小固定的栈:有初始化栈、入栈、出栈、返回栈顶等功能
- 提供变量size,用来记录栈中元素的数量。入栈+1,出栈-1。
对于用数组结构实现队列:有初始化队列、进队列,出队列等操作
- 定义变量start用来记录最早进入队列的元素下标,定义变量end用来记录后面进来元素的下标,size用来记录队列中元素的数目
code:
public class Array_To_Stack_Queue {
public static class ArrayStack {
private Integer[] arr;
private Integer size;
public ArrayStack(int initSize) {
if (initSize < 0) {
throw new IllegalArgumentException("The init size is less than 0");
}
arr = new Integer[initSize];
size = 0;
}
public Integer peek() {
if (size == 0) {
return null;
}
return arr[size - 1];
}
public void push(int obj) {
if (size == arr.length) {
throw new ArrayIndexOutOfBoundsException("The queue is full");
}
arr[size++] = obj;
}
public Integer pop() {
if (size == 0) {
throw new ArrayIndexOutOfBoundsException("The queue is empty");
}
return arr[--size];
}
}
public static class ArrayQueue {
private Integer[] arr;
private Integer size;
private Integer start;
private Integer end;
public ArrayQueue(int initSize) {
if (initSize < 0) {
throw new IllegalArgumentException("The init size is less than 0");
}
arr = new Integer[initSize];
size = 0;
start = 0;
end = 0;
}
public Integer peek() {
if (size == 0) {
return null;
}
return arr[start];
}
public void push(int obj) {
if (size == arr.length) {
throw new ArrayIndexOutOfBoundsException("The queue is full");
}
size++;
arr[end] = obj;
end = end == arr.length - 1 ? 0 : end + 1;
}
public Integer poll() {
if (size == 0) {
throw new ArrayIndexOutOfBoundsException("The queue is empty");
}
size--;
int tmp = start;
start = start == arr.length - 1 ? 0 : start + 1;
return arr[tmp];
}
}
public static void main(String[] args) {
ArrayStack stack = new ArrayStack(3);
stack.push(1);
stack.push(2);
stack.push(3);
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println("-----------------");
ArrayQueue queue = new ArrayQueue(3);
queue.push(1);
queue.push(2);
queue.push(3);
System.out.println(queue.poll());
System.out.println(queue.poll());
System.out.println(queue.poll());
}
}
reference:左神
encouragement:
生活中总是充满了选择和矛盾,请一定审视一下自己的内心,去争取那最珍贵的东西,可惜我一直做不到。