Java数据结构:栈

导读:
数据结构示意图↓
image


image


image


image

public class stack<T> {
    private int maxSize; //栈的大小
    private int top = -1; //栈顶指针
    private Object[] arr; //定义数组

    /** 
     * 初始化栈对象的大小
     */ 
    public stack(int maxSize) {
        this.maxSize = maxSize;
        this.arr = new Object[maxSize];
    }


    /** 
     * 入栈
     */ 
    public void Push(T o) {
        arr[++top] = o;
    }

    /** 
     * 出栈
     */ 
    public Object Pop() {
        Object tmp = arr[top];
        arr[top--] = null;
        return tmp;
    }


    public int getMaxSize() {
        return maxSize;
    }

    public int getTop() {
        return top;
    }

    public Object[] getArr() {
        return arr;
    }
}


public class stackT {
    public static void main(String[] args) {
        stack stk = new stack(10);
        stk.Push(55);
        stk.Push(88);
        stk.Push(88);
        stk.Push(88);
        stk.Push(88);
        System.out.println(stk.getTop() + "*********");
        Object pop = stk.Pop();
        Object pop1 = stk.Pop();
        Object pop0 = stk.Pop();
        Object pop2 = stk.Pop();
        Object pop3 = stk.Pop();

        System.out.println(pop0);
        System.out.println(pop1);
        System.out.println(pop2);
        System.out.println(pop3);
        System.out.println(pop);
        ;
    }
}

运行结果:
image

参考文章:

  1. 顺序栈及基本操作 http://c.biancheng.net/view/3350.html
  2. 力扣图解算法数据结构 https://leetcode.cn/leetbook/read/illustration-of-algorithm/50e446/
posted @ 2022-10-18 21:41  Little_Monster-lhq  阅读(20)  评论(0编辑  收藏  举报