一、栈
栈(stack),是一种线性表。先进后出,限定仅在表尾进行插入和删除操作的线性表。表尾这一端被称为栈顶,相对地,把另一端称为栈底。
二、代码如下
public class MyStack{
private T[] elem;
private int usedSize;
public MyStack(){
this.elem=(T[])new Object[10];
this.usedSize=0;
}
入栈代码:
先判断是否栈满,已满则无法入栈,因为在上面的构造函数里声明的大小是10,所以超过会满栈。
如果未满栈,则将val放入栈中,usedSize++
public void push(T val){
if(isFull()){
return;
}
this.elem[this.usedSize]=val;
this.usedSize++;
}
出栈代码
先判断是否栈空,否的话先把出栈的元素保存在data中,然后usedSize–,再返回data
public T pop(){
if(empty()){
throw new RuntimeException("栈为空!");
}
//先把出栈的元素保存到data中
T data=this.elem[this.usedSize-1];
this.usedSize--;
return data;
}
得到栈顶元素且不删除。
判断完是否为空后,返回栈顶元素。
public T peek(){
if(empty()){
throw new RuntimeException("栈为空!");
}
return this.elem[this.usedSize-1];
}
public boolean empty(){
if(this.usedSize==0){
return true;
}
return false;
}
public boolean isFull(){
if(this.usedSize==this.elem.length){
return true;
}
return false;
}
}