1、用数组实现栈
数组实现栈还是比较简单的,只需要额外定义一个下标用来记录当前栈顶的位置即可。
代码实现
/**
* 如何用数组实现栈
*/
public class ArrayImplStack {
int[] arr = new int[5];
int index = 0;
public void push(int x) {
if (index == arr.length) {
throw new RuntimeException("栈满了,不能添加!");
}
arr[index++] = x;
}
public int pop() {
if (index == 0) {
throw new RuntimeException("栈为空,没有元素可弹出!");
}
return arr[--index];
}
public int top() {
int top = index - 1;
return arr[top];
}
public boolean isEmpty() {
return index == 0;
}
public boolean isFull() {
return index == arr.length;
}
}
2、用数组实现队列
数组实现队列相对来说稍微复杂一点,需要利用环形数组的思想来解决,定义两个下标popIndex、pushIndex,分别用来表示弹出元素时的下标和添加元素时的下标,再定义一个变量size,用来判断当前数组是否已经满了或者为空。当popIndex或者pushIndex下标到达数组最大位置时,则回到0重新开始记录,就像一个环形一样。
代码实现
public class ArrayImplQueue {
int size = 0;
int popIndex = 0;
int pushIndex = 0;
int[] arr = new int[5];
int limit = 5;
public void push(int x) {
if (size < limit) {
arr[pushIndex] = x;
size++;
pushIndex = pushIndex < limit - 1 ? pushIndex + 1 : 0;
} else {
throw new RuntimeException("队列满了,不能添加!");
}
}
public int pop() {
if (size == 0) {
throw new RuntimeException("队列为空,没有元素可弹出!");
}
size--;
int x = arr[popIndex];
popIndex = popIndex < limit - 1 ? popIndex + 1 : 0;
return x;
}
}