用数组模拟栈
ArrayStack类:数组模拟栈类
public class ArrayStack {
private int maxSize;
private int[] stack;
private int top;
public int getTop() {
return top;
}
public ArrayStack(){
}
public ArrayStack(int maxSize){
this.maxSize = maxSize;
stack = new int[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;
}
stack[++top] = value;
}
public int pop(){
if(isEmpty()){
throw new RuntimeException("栈空!");
}
return stack[top--];
}
public void printStack(){
if(isEmpty()){
System.out.println("栈空!");
return;
}
for(int i = top; i >= 0; i--){
System.out.println(stack[i]);
}
}
}
UseArrayStack类:测试类
public class UseArrayStack {
public static void main(String[] args) {
ArrayStack stack = new ArrayStack(5);
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
stack.printStack();
stack.pop();
stack.printStack();
System.out.println(stack.getTop());
}
}
欢迎讨论