数组栈
栈类
class ArrayStack {
private int[] stack;
private int MaxSize;
private int top;
public ArrayStack(int MaxSize){
this.MaxSize = MaxSize;
stack = new int[this.MaxSize];
top = -1;
}
判断栈满或栈空
public boolean isFull(){
return top == MaxSize-1;
}
public boolean isEmpty(){
return top == -1;
}
入栈
public void push(int value){
if(isFull()){
System.out.println("栈满");
return;
}
top++;
stack[top] = value;
}
出栈
public void pop(){
if(isEmpty()){
System.out.println("栈空");
return;
}
int value = stack[top];
top--;
System.out.println(value);
}
打印栈中元素
public void show(){
if(isEmpty()){
System.out.println("栈空");
return;
}
for(int i= top;i<=0;i--){
System.out.println(stack[i]);
}
代码
package stack;
public class ArrayStackDemo {
public static void main(String[] args) {
ArrayStack stack = new ArrayStack(3);
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
System.out.println("--------");
stack.show();
System.out.println("-------");
stack.pop();
stack.pop();
stack.pop();
stack.pop();
}
}
class ArrayStack {
private int[] stack;
private int MaxSize;
private int top;
public ArrayStack(int MaxSize){
this.MaxSize = MaxSize;
stack = new int[this.MaxSize];
top = -1;
}
public boolean isFull(){
return top == MaxSize-1;
}
public boolean isEmpty(){
return top == -1;
}
public void push(int value){
if(isFull()){
System.out.println("栈满");
return;
}
top++;
stack[top] = value;
}
public void pop(){
if(isEmpty()){
System.out.println("栈空");
return;
}
int value = stack[top];
top--;
System.out.println(value);
}
public void show(){
if(isEmpty()){
System.out.println("栈空");
return;
}
for(int i= top;i<=0;i--){
System.out.println(stack[i]);
}
}
}