栈(Stack)的实现--顺序栈--Java

版权声明: https://blog.csdn.net/qq_16525279/article/details/82148289

java.util

Class Stack<E>

栈的基本操作,初始化、入栈、出栈、获取栈顶元素、判断栈是否为空、获取栈内元素个数。隐含功能:判断栈是否已满,如果已满,就需要扩容。

封装实现一个Stack,使用泛型作为栈内参数。

package d20180828.ch11;

import java.util.Arrays;

public class Stack<E> {

    private int size = 0;
    private Object[] array;
    // 默认初始化栈
    public Stack(){
        this(10);
    }

    //指定栈空间初始化
    public Stack(int initialCapacity){
        if(initialCapacity <= 0){
            throw new RuntimeException("初始化栈空间错误");
        }
        array = new Object[initialCapacity];
    }
    //入栈
    public E push(E item){
        ensureCapacityHelper(size+1);
        array[size++] = item;
        return item;
    }
    //获取栈顶元素
    public E peek(){
        if(isEmpty()){
            throw new IndexOutOfBoundsException("栈为空");
        }
        return (E) array[size-1];
    }
    //出栈
    public E pop(){
        E item = peek();
        size--;
        return item;
    }
    //栈是否为空
    public boolean isEmpty(){
        return size == 0;
    }
    public int size(){
        return size;
    }
    //确保空间够用
    private void ensureCapacityHelper(int minCapacity){
        if(minCapacity > array.length){
            grow();
        }
    }
    //涨空间
    private void grow(){
        int oldCapacity = array.length;
        int newCapacity = oldCapacity*2;
        if(newCapacity < oldCapacity){
            //说明溢出了
            throw new OutOfMemoryError();
        }else{
            array = Arrays.copyOf(array, newCapacity);
        }
    }
}

测试代码

package d20180828.ch11;

public class StackTest {

    public static void main(String[] args){
        Stack<String> s = new Stack<String>();
        s.push("a");
        s.push("b");
        System.out.println(s.pop());
        System.out.println(s.peek());
    }
}

猜你喜欢

转载自blog.csdn.net/qq_16525279/article/details/82148289