栈是什么?
1、栈是一个先入后出(FILO-First In Last Out)的有序列表。
2、栈(stack)是限制线性表中元素的插入和删除只能在线性表的同一端进行的一种特殊线性表。
允许插入和删除的一端,为变化的一端,称为栈顶(Top),另一端为固定的一端,称为栈底(Bottom)。
3、根据栈的定义可知,最先放入栈中元素在栈底,最后放入的元素在栈顶,而删除元素刚好相反,
最后放入的元素最先删除,最先放入的元素最后删除
栈的数组设计思路
- 定义一个 top 来表示栈顶的角标位置,初始化 为 -1
- 入栈的操作,当有数据加入到栈时, top++; stack[top] = data;
- 出栈的操作, int value = stack[top]; top--, return value
栈的数组代码实现
import java.util.Scanner;
public class ArrayStackDemo {
public static void main(String[] args) {
ArrayStrack strack = new ArrayStrack(4);
String key="";
boolean loop=true;
Scanner scanner = new Scanner(System.in);
while (loop){
System.out.println("show");
System.out.println("exit");
System.out.println("push");
System.out.println("pop");
//字符串
key=scanner.next();
switch (key){
case "show":
strack.list();
break;
case "exit":
scanner.close();
loop=false;
System.out.println("退出");
break;
case "push":
System.out.println("输入一个数");
int value=scanner.nextInt();
strack.push(value);
break;
case "pop":
try {
int r=strack.pop();
System.out.println("出栈的数据是"+r);
}catch (Exception e){
System.out.println(e.getMessage());
}
break;
default:
break;
}
}
System.out.println("程序退出");
}
}
class ArrayStrack{
private int maxSize;
private int[] stack;
private int top=-1;
public ArrayStrack(int maxSize) {
this.maxSize = maxSize;
stack= new int[maxSize];
}
public boolean isFull(){
if (top==maxSize-1){
return true;
}
return false;
}
public boolean isEmpty(){
if (top==-1){
return true;
}
return false;
}
public void push(int value){
if (isFull()){
System.out.println("栈满了");
}
top++;
stack[top]=value;
}
public int pop(){
if (isEmpty()){
//抛出异常
throw new RuntimeException("栈空,没有数据");
}
int value=stack[top];
top--;
return value;
}
public void list(){
if (isEmpty()){
System.out.println("栈空没有数据了");
return;
}
for (int i=top;i>=0;i--){
System.out.println("stack["+i+"]="+stack[i]);
}
}
}