手写数据结构-基于动态数组的栈

1.栈基础

结构特性:先进后出

2.手写基于动态链表的栈
package com.tc.javabase.datastructure.array.stack;

import com.tc.javabase.datastructure.array.ArrayList;
import com.tc.javabase.datastructure.stack.Stack;

/**
 * 基于动态数组实现的栈
 *
 *  * 结构特性:先进后出
 *  *
 *  * 时间复杂度分析:
 *  *      入栈:         O(1)
 *  *      出栈:         O(1)
 *  *      查询栈顶元素:  O(1)
 *  *
 *  * 综上所述: 基于动态数组的操作时间复杂度都是O(1)
 * @param 
 */
public class ArrayStack implements Stack {

    private ArrayList arrayList;

    public ArrayStack(int capacity){
        arrayList = new ArrayList<>(capacity);
    }

    public ArrayStack(){
        arrayList = new ArrayList<>();
    }

    @Override
    public int getSize(){
        return arrayList.getSize();
    }

    @Override
    public boolean isEmpty(){
        return arrayList.isEmpty();
    }

    public int getCapacity(){
        return arrayList.getCapacity();
    }

    @Override
    public void push(E e){
        arrayList.addLast(e);
    }

    @Override
    public E pop(){
        return arrayList.removeLast();
    }

    @Override
    public E peek(){
        return arrayList.getLast();
    }

    @Override
    public String toString(){
        StringBuilder res = new StringBuilder();
        res.append("Stack: ");
        res.append('[');
        for(int i = 0; i < arrayList.getSize() ; i ++){
            res.append(arrayList.get(i));
            if(i != arrayList.getSize() - 1)
                res.append(", ");
        }
        res.append("] top");
        return res.toString();
    }
}

你可能感兴趣的:(手写数据结构-基于动态数组的栈)