栈的基本操作--java实现

package com.wyl.linklist;
/**
 * 栈的定义及相关操作
 * 用数组实现栈
 * 栈是一个线性表,不过进栈和出栈操作在表尾操作
 * @author wyl
 *
 */
public class MyStack {

    private static final Integer STACKSIZE = 100; //声明栈的容量
    private Integer base; //栈底索引
    private Integer top; //栈顶索引
    
    private Integer[] stack; //声明栈,用数组实现
    
    public MyStack(){
        base = top = -1; //空栈
        stack = new Integer[STACKSIZE];
    }
    /**
     * 栈判空
     */
    public boolean isEmpty(){
        return top == base;  //栈顶与栈底指向同一空间即为空栈
    }
    /**
     * 栈判满
     */
    public boolean isFull(){
        return top >= STACKSIZE-1;
    }
    /**
     * 入栈
     */
    public void push(Integer data){
        if(isFull()){
            System.out.println("栈已满");
        }else{
            stack[++top] = data;
        }
    }
    
    /**
     * 出栈操作
     */
    public void pop(){
        if(isEmpty()){
            System.out.println("栈为空");
        }else{
            System.out.println(stack[top--]);
        }
    }
    
    /**
     *  清空栈
     */
    public void clear(){
        if(!isEmpty()){
            int size = top-base;
            for(int i=0;i<size;i++){
                stack[i]=null;
            }
            top = base = -1;
        }
    }
    public static void main(String[] args) {
        MyStack myStack = new MyStack();
        myStack.push(23);
        myStack.push(24);
        myStack.push(25);
        myStack.push(26);
        myStack.pop();
        myStack.pop();
        myStack.pop();
        myStack.pop();
        myStack.pop();
        myStack.clear();
        myStack.pop();
    }
}
原文地址:https://www.cnblogs.com/studyDetail/p/7204904.html