欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

数组实现栈的简单实现

程序员文章站 2022-07-10 23:31:02
...
package com.bobo.buildDataStructure;

import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * User: bobo
 * Date: 2019/9/10
 * Description: 用数组实现栈
 */
public class ArrayStack<E> {

    private Object[] array = new Object[0];
    //指针,固定指向栈顶
    private int index = -1;

    //测试方法
    public static void main(String[] args) {
        ArrayStack stack = new ArrayStack();
        System.out.println("stack.isEmpty = " + stack.isEmpty());
        stack.push(1);
        stack.push(2);
        stack.push(3);
        stack.push(4);
        System.out.println("stack.isEmpty = " + stack.isEmpty());
        System.out.println("stack = " + stack.search(3));
        System.out.println("stack = " + stack.peek());
        System.out.println("stack = " + stack.pop());
        System.out.println("stack = " + stack.pop());
    }

    public E push(E object) {
        array = Arrays.copyOf(array,array.length+1);
        array[++index] = object;
        return object;
    }

    public E pop() {
        if (index == -1) {
            return null;
        }
        E object = (E) array[index];
        array[index--] = null;
        return object;
    }

    public E peek() {
        if (index == -1) {
            return null;
        }
        return (E) array[index];
    }

    /**
     * 距离栈顶的距离,需要倒序
     *
     * @param object
     * @return
     */
    public int search(E object) {
        if (index == -1) {
            return -1;
        }
        if (object == null) {
            for (int i = array.length - 1; i >= 0; i--) {
                if (array[i] == null) {
                    return array.length - i;
                }
            }
        } else {
            for (int i = array.length - 1; i >= 0; i--) {
                if (array[i].equals(object)) {
                    return array.length - 1;
                }
            }
        }
        return -1;
    }

    public boolean isEmpty() {
        return index == -1;
    }
}