1.栈
栈相对于开放的数组而言,是访问受限的
栈只允许访问一个数据项,即最后插入的数据项,移除这个数据项后才能访问倒数第二个数据项
栈的特点:先进后出
2.源码实现
public class StackDemo {
private String[] arr;//数组
private int arrSize;//数组长度
private int top;//顶端元素index
public StackDemo(int size) {
if(size <= 0){
throw new IllegalArgumentException("illegal size:"+size);
}
arr = new String[size];
arrSize = size;
top = 0;
}
//添加元素
public void push(String str){
if(!isFull()){
arr[top++] = str;
}
}
//弹出头部元素
public String pop(){
if(!isEmpty()){
return arr[--top];
}
return "";
}
//获取头部元素
public String peek(){
if(!isEmpty()){
return arr[top-1];
}
return "";
}
public boolean isEmpty(){
return top == 0;
}
public boolean isFull(){
return top == arrSize;
}
}