2025-01-13 用数组实现栈

This commit is contained in:
liangjinglin 2025-01-13 20:51:53 +08:00
parent 11bca22901
commit ca2ce0d684

View File

@ -0,0 +1,111 @@
package stack;
import queue.ArrayQueue;
import java.util.Scanner;
public class ArrayStack {
private int top = -1;
private int maxSize;
private int[] stack;
public ArrayStack(int maxSize) {
this.maxSize = maxSize;
stack = new int[maxSize];
}
public int getTop() {
return top;
}
public void setTop(int top) {
this.top = top;
}
public int getMaxSize() {
return maxSize;
}
public void setMaxSize(int maxSize) {
this.maxSize = maxSize;
}
public int[] getStack() {
return stack;
}
public void setStack(int[] stack) {
this.stack = stack;
}
public boolean isFull(){
return top == maxSize - 1;
}
public boolean isEmpty(){
return top == -1;
}
public void push(int data){
if(isFull()){
System.out.println("栈满,无法加入新数据");
return;
}
top ++;
stack[top] = data;
}
public int pop(){
if(isEmpty()){
throw new RuntimeException("栈空了");
}
int value = stack[top];
top --;
return value;
}
public int top(){
if(isEmpty()){
throw new RuntimeException("栈空了");
}
int value = stack[top];
return value;
}
public void show(){
if(isEmpty()){
System.out.println("栈空");
}
for(int i = top; i >= 0; i--){
System.out.printf("stack[%d]=%d\n", i, stack[i]);
}
}
public static void main(String[] args) {
ArrayStack arrayStack = new ArrayStack(5);
Scanner scan = new Scanner(System.in);
while (true) {
System.out.println("a存数, g取数, s查看, exit退出:");
String handle = scan.next();
if ("exit".equals(handle)){
break;
}
if ("a".equals(handle)){
System.out.println("请输入入队数据:");
int data = scan.nextInt();
arrayStack.push(data);
}
if ("g".equals(handle)){
int value = arrayStack.pop();
System.out.println("取出的数为:" + value);
}
if ("s".equals(handle)){
arrayStack.show();
}
}
scan.close();
}
}