/**
* 静态栈演示代码
*/
package com.szy.structure.stack;
import java.util.Scanner;
public class StaticStack {
private final int SIZE=5;
private int top;
private int[] stackArray=null;
StaticStack(){
top=-1;
stackArray=new int[SIZE];
}
/**
* 检查栈是否已满
* @return
*/
public boolean isFull()
{
if (top==SIZE-1) {
return true;
}
return false;
}
/**
* 检查栈是否为空
* @return
*/
public boolean isEmpty()
{
if (top==-1) {
return true;
}
return false;
}
/**
* 压栈
* @param info
*/
public void push(int info){
top++;
stackArray[top]=info;
System.out.println(info+" 被压入栈中");
}
/**
* 出栈
*/
public void pop(){
System.out.println(stackArray[top]+" 出栈成功");
top--;
}
/**
* 输出栈中信息
*/
public void display(){
if (isEmpty()) {
System.out.println("空栈");
}
else {
System.out.println("栈中信息:");
for(int i=top;i>-1;i--){
System.out.print(stackArray[i]+" ");
}
System.out.println("\n");
}
}
public static void main(String[] args) throws Exception {
StaticStack stack=new StaticStack();
int choice=0;
while(true)
{
System.out.println("---MENU---");
System.out.println("1.Push");
System.out.println("2.Pop");
System.out.println("3.Display");
System.out.println("4.Exit");
System.out.println("----------");
System.out.println("请选择:");
Scanner scanner=new Scanner(System.in);
choice=scanner.nextInt();
switch (choice) {
case 1:
{
if (stack.isFull()) {
System.out.println("栈已满!");
break;
}
System.out.println("请输入数字:");
int input=scanner.nextInt();
stack.push(input);
}
break;
case 2:
{
if (stack.isEmpty()) {
System.out.println("空栈!");
break;
}
stack.pop();
}
break;
case 3:
{
stack.display();
}
break;
case 4:
return;
default:
System.err.println("无效的输入!");
break;
}
}
}
}