数据结构(一)
1、栈(先进后出的数据结构)
1.1、使用Java数组实现栈如下所示:
/**
* 使用数组来模拟栈
*/
public class ArrayStack {
//栈的大小
private int SIZE = 0;
//一维数组
int[] arrayStack;
//栈顶指针
private int top = -1; //等于-1时表示栈中没有任何数据
//初始化栈的大小
public ArrayStack(int size) {
this.SIZE = size;
arrayStack = new int[size];
}
//判断是否满栈
public boolean isFullStack() {
return this.top == SIZE - 1;
}
//判断栈是否为空
public boolean isEmpty() {
return this.top == -1;
}
//压栈操作
public void addStack(int value) {
if (isFullStack()) {
throw new RuntimeException("此栈已满!");
}
//栈顶指针自增
this.top++;
arrayStack[top] = value;
}
//弹栈
public int popStack() {
//如果栈为空,则抛出异常
if (isEmpty()) {
throw new RuntimeException("栈为空!");
}
int value = arrayStack[top];
this.top--;
return value;
}
//查看栈中的所有数据
public void showStack() {
//如果栈为空,则抛出异常
if (isEmpty()) {
throw new RuntimeException("栈为空!");
}
for (int i = 0; i < this.top; i++) {
System.out.print(arrayStack[i] + "\t");
}
}
}
//测试类
public class Test1 {
public static void main(String[] args) {
//创建一个栈
ArrayStack arrayStack = new ArrayStack(120);
//循环压栈
for (int i = 0; i < 10; i++) {
arrayStack.addStack(i + 1);
}
//打印栈中所有的数据
arrayStack.showStack();
System.out.println("\n----------------------------------");
//循环出栈并且打印
while (arrayStack.isEmpty()){
System.out.print(arrayStack.popStack() + "\t");
}
//再次打印栈中所有的数据
arrayStack.showStack();
}
}
输出结果:
1 2 3 4 5 6 7 8 9
----------------------------------
1 2 3 4 5 6 7 8 9
进程已结束,退出代码0