数据结构与算法 使用数组实现栈(stack)

栈这种数据结构有FILO(First-In-Last-Out)的特性,恰好和队列FIFO的特性相异。前面我们介绍了队列也通过代码实现了以数组为基础结构实现的队列,这篇博客我们来介绍Stack,并且使用数组来实现 (链表实现性能稍差)。

  • 栈的结构像桶一样,只不过每次只能放入和取出一个元素,所以Stack才有FILO这种特性。
  • 栈的底部被成为栈底(Bottom),顶部称为栈顶(top)。
  • 每次把元素放入栈入栈被称为入栈(Push),最先入栈的元素被压在栈底。
  • 每次把元素取出栈被称为入栈(Pop),最先出栈的元素是在栈顶的元素。

在这里插入图片描述
在这里插入图片描述

  • 在实现代码前,我们来规定:
  1. 栈的最多能容纳MaxSize个元素。
  2. 有个虚拟的指针p(整数类型的变量)标记栈顶;当栈空时,p等于-1;当栈满时,p等于MaxSize - 1。
  • 数组实现栈:
public class ArrayStack {
    private int MaxSize;
    private int p;
    private int [] stack;

    public ArrayStack(int MaxSize){
        this.MaxSize = MaxSize;
        this.p = -1;
        this.stack = new int[MaxSize];
    }

    /**
     * Judge if the stack is full.
     * @return
     */
    public boolean isFull(){
        return this.p == this.MaxSize - 1;
    }

    /**
     * Push a element into the stack.
     * @param element
     */
    public void Push(int element){
        if(!this.isFull()){
            this.stack[++ this.p] = element;
            return;
        }
        System.out.println("Stack is full.");
    }

    /**
     * Judge if the stack is empty.
     * @return
     */
    public boolean isEmpty(){
        return this.p == -1;
    }

    /**
     * Pop a element out.
     * @return
     */
    public int Pop(){
        if(this.isEmpty()){
            System.out.println("The stack is empty");
            return Integer.MIN_VALUE;
        }
        return this.stack[this.p --];
    }

    public static void main(String[] args) {
        ArrayStack arrayStack = new ArrayStack(10);
        for(int i = 1;i <= 10;i ++){
            arrayStack.Push(i);
        }
        for (int j = 0;j < 10;j ++){
            System.out.println(arrayStack.Pop());
        }
    }
}
  • 这里巧用了自增、自减运算符,因此代码量比较少。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章