定义栈的接口
public interface IStack<E> {
E push(E item); //入栈
E pop(); //出栈
E peek(); //取栈顶元素
int size(); //返回栈中元素的个数
boolean empty(); //判断栈是否为空
}
实现接口
import java.lang.reflect.Array;
public class SeqStack<E> implements IStack<E> {
private int maxsize;
private int top;
private E[] data;
public SeqStack(Class <E> type,int maxsize){
this.maxsize=maxsize;
top=-1; //栈为空top为-1
data = (E[])Array.newInstance(type, maxsize);
}
//入栈
public E push(E item) {
if(!isfull()){
data[++top]=item;
return item;
}
else
return null;
}
//取出栈顶数据
public E pop() {
if(!empty())
return data[top--];
else
return null;
}
public E peek() {
if(!empty()){
return data[top];
}
else
return null;
}
public int size() {
return top+1;
}
public boolean empty() {
if(top==-1)
return true;
else
return false;
}
public boolean isfull(){
if(top==maxsize-1)
return true;
else
return false;
}
}