数组实现stack

2019-01-09  本文已影响12人  良人与我

在 Java 中 Stack 类表示后进先出(LIFO)的对象堆栈。栈是一种非常常见的数据结构,它采用典型的先进后出的操作方式完成的。每一个栈都包含一个栈顶,每次出栈是将栈顶的数据取出
下面通过数组来实现栈的出列入列 操作。

package com.river.stack;

import com.google.gson.Gson;


public class ArrayStack<T> {
    int size;
    private int count;

    private Object[] items;

    public ArrayStack(int size) {
        this.size = size;
        items = new Object[size];
    }

    public boolean put(T item){
        if(count >= size){
            return false;
        }
        items[count++] = item;
        return true;
    }
    public T pop(){
        if(count == 0){
            return null;
        }
        T item = (T)items[count-1];
        items[count-1] = null;
        count--;
        return item;
    }
    public void show(){
        System.out.println(new Gson().toJson(this));
    }

    public static void main(String[] args) {
        ArrayStack<String> arrayStack = new ArrayStack<>(5);
        arrayStack.put("hello");
        arrayStack.put("river");
        arrayStack.put("fan");
        arrayStack.put("frank");
        arrayStack.put("luck");
        arrayStack.put("lily");
        arrayStack.show();
        System.out.println(arrayStack.pop());
        System.out.println(arrayStack.pop());
        System.out.println(arrayStack.pop());
        arrayStack.show();
    }


}

打印结果如下
如果超过栈的容量,put 操作会失败。
pop是先入后出

{"size":5,"count":5,"items":["hello","river","fan","frank","luck"]}
luck
frank
fan
{"size":5,"count":2,"items":["hello","river",null,null,null]}

上一篇 下一篇

猜你喜欢

热点阅读