1.栈的定义:
栈是限定仅在表尾进行插入和删除操作的线性表,允许插入、删除的一端称为栈顶(top),另一端称为栈底(botton),不含任何数据元素的栈称为空栈。
★栈遵循先进后出的原则。
2.顺序栈:没有指针域,需要确定一个固定长度,时间复杂度为O(1)。
顺序栈泛型类的定义如下:
package exercise_数据结构_顺序栈;
public class sequenceStack<T> {
final int MaxSize = 10;
private T[] stackArray;
private int top;
public sequenceStack() {
top = -1;
stackArray = (T[]) new Object[MaxSize];
}
public sequenceStack(int n) {
if (n <= 0) {
System.out.println("数组长度大于0,否则退出程序运行");
System.exit(1);
}
top = -1;
stackArray = (T[]) new Object[n];
}
public void push(T obj) { //入栈
if (top == stackArray.length - 1) {
T[] p = (T[]) new Object[top * 2 + 2];
for (int i = 0; i < top; i++) {
p[i] = stackArray[i];
stackArray = p;
}
}
top++;
stackArray[top] = obj;
}
public T pop(){ //出栈
if (top == -1){
System.out.println("数据栈为空,无法删除数据");
return null;
}
top--;
return stackArray[top + 1];
}
public boolean isEmpty(){ //判断栈空
return top == -1;
}
public int size(){ //求栈的长度
return top + 1;
}
public void nextOrder(){ //遍历栈
for (int i = top; i >= 0 ; i--) {
System.out.print(stackArray[i]+"\t");
}
}
public void clear(){ //清空栈操作
top = -1;
}
}
注意:
上溢:入栈时应该先判断栈是否满了,栈满时不能入栈,否则会出现空间溢出。
下溢:出栈时应该先判断栈是否为空,栈空时不能操作,否则会出现空间溢出。
测试类:
package exercise_数据结构_顺序栈;
public class Test<T> {
public static void main(String[] args) {
sequenceStack<Integer> stack = new sequenceStack<>(); //无参为默认长度 MaxSize
int []x = {20,30,15,11,60,88,55};
for (int i = 0; i <= x.length - 1; i++) {
stack.push(x[i]);
}
System.out.println("遍历顺序栈:");
stack.nextOrder();
}
}
运行截图: