栈模型:栈也是一种线性数据结构
栈是限制插入与删除只能在同一位置的进行的表,该位置位于表的末端,叫做栈的顶(top)
对栈的基本操作:
进栈(push):相当于向表中插入数据
出战(pop):相当于从表中删除数据,出栈是删除最后插入的元素
栈的操作特点:先进后出,后进先出;先入栈的数据最后出栈,后入栈的数据先出栈
目前两种流行实现栈表的方式:一、链式结构,二、使用数组来实现。二者都简化了ArrayList与LinkedList中的逻辑
栈的数组实现:
栈的数组实现是在数组的一端进行入栈(添加元素)、出栈(取元素) 操作;由于数组的特性,一般把数组最后一个元素作为
栈顶
/**
* 栈的数组实现
*/
public class ArrayStack<T> {
private T[] theArray;//定义数组,用来存放数据
private int theSize;//数组的大小(栈的容量)
private int topOfStack;//数组内元素的个数
/**
* 构造方法,创建一个空数组(空栈)
*/
public ArrayStack(){
theArray = null;
theSize = 0;
topOfStack = 0;
}
/**
* 构造方法,创建一个指定容量的数组(栈)
* @param theSize
*/
public ArrayStack(int theSize){
theArray = (T[]) new Object[theSize];
this.theSize = theSize;
this.topOfStack = 0;
}
/**
* 返回栈内元素的个数
* @return
*/
public int getTopOfStack(){
return topOfStack;
}
/**
* 判断栈是否已满
* @return
*/
public boolean ifFull(){
if(topOfStack == theSize){
return true;
}
return false;
}
/**
* 判断栈是否为空
* @return
*/
public boolean isEmpty(){
return topOfStack == 0;
}
/**
* 入栈
* @param value
*/
public void push(Object value){
//判断栈是否已满
if(this.ifFull()){
throw new RuntimeException("Stack is Full");
}
/**
* 向数组中添加数据,从下标0处依次往后加;下次添加元素的数组下标的值=当前数组内元素的个数的值
*/
theArray[topOfStack] = (T) value;
topOfStack++;
}
/**
* 出栈
* @return
*/
public T pop(){
//判断栈是否已空
if(this.isEmpty()){
throw new RuntimeException("Stack is Empty");
}
/**
* 由于栈满足先进后出,后进先出的原则,所以基于数组的栈,出栈时是取下标最大的那个数组元素
*/
T t = theArray[topOfStack-1];
topOfStack--;
//设置数组最后一位为null,即删除下标为topOfStack-1的数组元素
theArray[topOfStack] = null;
return t;
}
/**
* 返回栈顶元素
* @return
*/
public T peak(){
//
if(this.isEmpty()){
return null;
}
//返回数组中下标最大的元素
return theArray[topOfStack-1];
}
}