1、通过数组进行实现栈的功能
2、通过top指针实现入栈和出栈
import java.util.Stack;
public class ArrayStack {
public static void main(String[] args) {
StackStruct s = new StackStruct(5);
try {
s.push(1);
s.push(2);
s.push(3);
s.push(5);
s.push(5);
System.out.println();
s.show();
// 修改
System.out.println();
s.upDate(5, 4);
s.upDate(6, 4);
s.show();
// System.out.println();
// s.pop();
// s.pop();
// s.push(6);
// System.out.println();
// s.show();
} catch (Exception e) {
e.printStackTrace();
}
}
}
// 定义一个栈的结构体struct
class StackStruct {
private int maxSize; // 栈的大小
private int[] stack; // 数组
private int top; // 栈顶指针
// 构造器
public StackStruct(int maxSize) {
this.top = -1;
this.maxSize = maxSize;
this.stack = new int[maxSize];
// 全部赋值为-1
for (int i = 0; i < stack.length; i++) {
stack[i] = -1;
}
}
// 判断栈是否为空
public boolean isEmpty2() {
return top == -1;
}
public boolean isEmpty() {
boolean indentify = true;
for (int i = 0; i < stack.length; i++) {
if (stack[i] != -1) {
indentify = false;
break;
}
}
return indentify;
}
// 判断栈是否为满
public boolean isFull2() {
return top == stack.length - 1;
}
public boolean isFull() {
boolean indentify = true;
for (int i = 0; i < stack.length; i++) {
if (stack[i] == -1) {
indentify = false;
break;
}
}
return indentify;
}
// 定义入栈方法
public void push(int n) {
if (isFull()) {
throw new RuntimeException("栈已满!");
// System.out.println("栈已满!");
// return;
}
stack[++top] = n;
System.out.println("入栈: " + n);
}
// 定义出栈方法
public void pop() {
if (isEmpty()) {
throw new RuntimeException("栈为空!");
// System.out.println("栈为空!");
// return;
}
int value = stack[top];
stack[top] = -1;
top--;
System.out.println("出栈:" + value);
}
// 修改栈内第一次存入的元素
public void upDate(int value, int data) {
if (data == -1) {
System.out.println("修改的数据不合法");
return;
}
for (int i = 0; i < stack.length; i++) {
if (value == stack[i]) {
stack[i] = data;
System.out.println("修改完成!");
break;
} else if (i == stack.length - 1) { // 查询到最后,没有符合原值的数
System.out.println("对于原始数据:" + value + ",无法在栈中找到相应的元素进行修改");
}
}
}
// 查看栈内元素
public void show() {
if (isEmpty()) {
throw new RuntimeException("栈为空");
// System.out.println("栈为空");
// return;
}
int num = 0;
System.out.println("序号" + ":" + "值");
for (int i = 0; i < stack.length; i++) {
// 找到非空的栈元素个数,进而将个数当作非空长度进行输出
// 满栈的情况
if (i == stack.length - 1) {
num = i;
break;
} else if (stack[i + 1] == -1) {
num = i;
break;
}
}
for (int j = num; j >= 0; j--) {
System.out.println(j + " : " + stack[j]);
}
}
}