栈的基本结构(线性结构)

1.栈

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

栈容器类

public class MyStack<E> {
private Object[] arr;//存放元素的物理结构
private int stackLength = 4;//数组的默认长度
private int size; //记录栈容器的元素个数
private int index = -1;//操作数组下标位置的指针
/**判断栈容器是否为空**/
public boolean empty(){
return false;
}
/** 获取栈顶元素**/
public E pop(){
return null;
}
/**向栈容器中添加元素**/
public E push(E item){
return null;
}
public static void main(String[] args){
 }
}

实现添加元素

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];
    }
//以 1.5 倍对数组扩容
   if(this.size - (this.stackLength-1) >= 0{
    this.stackLength = this.stackLength + (this.stackLength >> 1);
     this.arr = Arrays.copyOf(this.arr,this.stackLength);
      }
}

获取元素

public E pop(){
//如果栈容器中没有元素则抛出异常
if(this.index == -1){
throw new EmptyStackException();
}
//记录元素个数
this.size--;
//返回栈顶元素
return (E) this.arr[index--];
}

判断栈容器是否为空

public boolean empty(){
return this.size == 0
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值