实现栈的思路分析
1.初始化一个top=-1,来表示栈顶;
2.入栈的操作:当有数据加入时,top++;stack[top]=data;
3.出栈的操作:int value = stack[pop]; pop–;return value;
代码实现
方法实现
package com.company;
public class ArrayStack {
private int maxSize;//栈的大小
private int[] stack;//数组模拟栈
private int top = -1;//top表示栈顶,初始化为-1
public ArrayStack(int maxSize){
this.maxSize =maxSize;
stack = new int[maxSize];
}
public boolean isFull(){
return top == maxSize-1;
}
public boolean isEmpty(){
return top==-1;
}
//入栈
public void push(int value){
if(isFull()){
System.out.println("the stack is filled");
return;
}
top++;
stack[top]=value;
}
//出栈
public int pop(){
if(isEmpty()){
// System.out.println("the stack is empty");
//抛出异常
throw new RuntimeException("the stack is empty!");
}
int value = stack[top];
top--;
return value;
}
public void list(){
if(isEmpty()){
System.out.println("the stack is empty!");
return;
}
for(int i=top;i>=0;i--){
System.out.printf("stack[%d]=%d\n",i,stack[i]);
}
}
}
main函数
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// write your code here
ArrayStack stack = new ArrayStack(4);
String key = "";
boolean loop = true;
Scanner scanner = new Scanner(System.in);
while (loop){
System.out.println("show:show the stack");
System.out.println("exit:exit the program");
System.out.println("push:push into the stack");
System.out.println("pop:popping");
key = scanner.next();
switch (key){
case "show":
stack.list();
break;
case "push":
System.out.println("enter a number");
int value = scanner.nextInt();
stack.push(value);
break;
case "pop":
try {
int res = stack.pop();
System.out.println(res);
}catch (Exception e){
e.printStackTrace();
}
break;
case "exit":
scanner.close();
loop = false;
break;
default:
break;
}
}
}
}