栈结构(Java实现)

一.栈结构

1.栈是一种只能从一端存取数据且遵循 "后进先出(LIFO)" 原则的线性存储结构。

2.实现栈容器

import java.util.Arrays;
import java.util.EmptyStackException;

/**
 * 自定义栈容器
 */
public class MyStack<E> {
    private Object[] arr;//存放元素的物理结构
    private int stackLength=4;//数组的默认长度
    private int size;//记录栈容器中的元素个数
    private int index=-1;//操作数组下标位置的指针

    /**
     * 判断栈容器是否为空
     * @return
     */
    public boolean empty(){
        return this.size==0;
    }

    /**
     * 获取栈顶元素
     * @return
     */
    public E top(){
        //没有元素抛出异常
        if(this.index==-1){
            throw new EmptyStackException();
        }
        //记录元素个数
        this.size--;
        //返回栈顶元素
        return (E) this.arr[index--];
    }
    /**
     * 向栈容器中添加元素
     * @param item
     * @return
     */
    public E push(E item){
        //初始化数组
        this.capacity();
        //添加元素
        this.arr[++index]=item;
        //记录元素个数
        this.size++;
        return item;
    }
    /**
     * 初始化数组或者以1.5倍进行扩容
     */
    private void capacity(){
        //数据初始化
        if(this.arr==null){
            this.arr=new Object[this.stackLength];
        }
        //对数组扩容
        if(this.size-(this.stackLength-1)>=0){
            this.stackLength=this.stackLength+(this.stackLength>>1);
            this.arr=Arrays.copyOf(this.arr, this.stackLength);
        }
    }
    public static void main(String[] args) {
        
    }
    
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值