栈(Stack)是一种特殊的线性表,其包括顺序栈(SeqStack)和链式栈(LinkedStack)。
栈的基本操作包括创建栈、判断栈是否为空(isEmpty)、入栈(push)、出栈(pop)和取栈顶元素(get)等,其实现的接口如下所示:
public interface SStack<T>{
boolean isEmpty(); //判断栈是否为空
void push(T x); //入栈
T pop(); //出栈
T get(); //获取栈顶元素
}
1、顺序栈(SeqStack)
public class SeqStack<T> implement SStack<T>{
private Object element[]; //存储栈数据元素的数组
private int top; //栈顶元素下标
public SeqStack(int size){ //构造容量为size大小的空栈
this.element = new Object[size];
this.top = -1;
}
public SeqStack(){ //构造初始化大小为64的空栈
this(64);
}
public boolean isEmpty(){ //栈空时返回true
return this.top==-1;
}
public void push(T x){ //元素x入栈
if(x==null) return; //元素x为空时不能入栈
if(this.top==element.length-1){ //栈满时,需要申请更大容量的栈空间
Object[] temp = this.element;
this.element = new Object[temp.length*2];
for(int i=0;i<temp.length;i++){
this.element[i] = temp[i];
}
this.element[this.top++] = x;
}
public T pop(){ //出栈
return this.top==-1?null:this.element[this.top--];
}
public T get(){ //取栈顶元素
return this.top==-1?null:this.element[this.top];
}
}
2、顺序栈(SeqStack)
public class LinkedStack<T> implements SStack<T>{
private Node<T> top;
public LinkedStack(){
this.top = null;
}
public boolean isEmpty(){
return this.top == null;
}
public void push(T x){
if(x!=null){
this.top = new Node(x,this.top); //头插入,x节点作为新的栈顶节点
}
}
public T pop(){
if(this.top==null) return null;
T temp = this.top.data;
this.top = this.top.next;
return temp;
}
public T get(){
return this.top==null?null:this.top.data;
}
}
/**
*单链表节点构造函数
*/
public class Node<T>{
public T data;
public Node<T> next;
public Node(T data,Node<T> next){
this.data = data;
this.next = next;
}
public Node(){
this(null,null);
}
}