栈特点先进后出
下面用java实现一个简单的栈
import java.util.Scanner;
/**
* @Author: taoqianlilang
* @Description:
* @Date: Created in 11:09 2020/4/7
* @Modified By:
*/
public class ArrayStackDemo {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
boolean loop=true;
String key="";
ArrayStack stack=new ArrayStack(4);
while (loop){
System.out.println("show :显示栈的顺序");
System.out.println("exit :退出程序");
System.out.println("push :入栈");
System.out.println("pop :出栈");
System.out.println("输入你的选择");
key=sc.nextLine();
switch (key){
case "show":
stack.list();
break;
case "exit":
sc.close();
loop=false;
break;
case "push":
System.out.println("输入需要入栈的数字");
int value = sc.nextInt();
sc.nextLine();
stack.push(value);
break;
case "pop":
System.out.println("弹出的内容为");
System.out.println(stack.pop());
break;
default:
break;
}
}
System.out.println("程序退出");
}
}
class ArrayStack{
private int maxSize;
private int[] stack;
private int top=-1;
/**
* @param maxSize 栈最大容量
*/
public ArrayStack(int maxSize) {
this.maxSize = maxSize;
stack=new int[maxSize];
}
//判断栈满
public boolean isFull(){
if (top==maxSize-1){
System.out.println("栈满");
return true;
}
return false;
}
public boolean isEmpty(){
if (top==-1){
System.out.println("栈空");
return true;
}
return false;
}
public void push(int value){
if (isFull()){
return;
}
top++;
stack[top]=value;
}
public int pop(){
if (isEmpty()){
return -1;
}
int value=stack[top];
top--;
return value;
}
/**
* 显示栈的情况
*/
public void list(){
if (isEmpty()){
System.out.println("栈空");
}
for (int i=top;i>=0;i--){
System.out.println("栈号为 :"+i+"值为 :"+stack[i]);
}
}
}