栈是一种具有特定操作规则的数据结构,遵循先进后出
(FILO)的原则,即最后进入的元素最先被访问或移除。栈通常用于需要临时存储数据,以及实现逆序输出、函数调用和表达式求值等场景。
基本操作:
创建栈、压栈(入栈)、弹栈(出栈)、获取栈顶元素、判断栈是否为空等。
代码如下:
import java.util.EmptyStackException;
class Stack {
private int maxSize;
private int[] stackArray;
private int top;
public Stack(int size) {
this.maxSize = size;
this.stackArray = new int[maxSize];
this.top = -1;
}
public void push(int value) {
if (top == maxSize - 1) {
System.out.println("Stack is full. Cannot push element.");
return;
}
stackArray[++top] = value;
}
public int pop() {
if (top == -1) {
throw new EmptyStackException();
}
return stackArray[top--];
}
public int peek() {
if (top == -1) {
throw new EmptyStackException();
}
return stackArray[top];
}
public boolean isEmpty() {
return top == -1;
}
}
测试:
public class Main {
public static void main(String[] args) {
Stack stack = new Stack(5);
stack.push(1);
stack.push(2);
stack.push(3);
System.out.println("Top element: " + stack.peek());
System.out.println("Pop element: " + stack.pop());
System.out.println("Is stack empty? " + stack.isEmpty());
}
}
标签:stackArray,int,top,public,算法,使用,Stack,数据结构,stack
From: https://blog.csdn.net/2401_82884096/article/details/136962820