--------------------------------------------------------------------------栈的接口定义--------------------------------------------
package com.cn.hbut.dao;
/**
* @author Administrator
* description:
* 栈的接口定义
*/
public interface Stacks {
public void clear();
public int length();
public boolean full();
public boolean empty();
//把元素e入栈
public boolean pushs(Object e);
//出栈
public Object pops();
//获取栈顶元素
public Object getTop();
}
--------------------------------------------------------------------------栈的具体实现----------------------------------------------------------------
package com.cn.hbut.daoImpl;
import com.cn.hbut.dao.Stacks;
/**
* @author Administrator
* description:
* 顺序栈的具体实现
*/
public class SqStack implements Stacks{
Object []elem;
int top;
int maxlen;
//默认的初始大小
public SqStack() {
top=-1;
maxlen=10;
elem=new Object[maxlen];
}
//自定义栈的大小
public SqStack(int maxlen) {
this.top = -1;
this.maxlen = maxlen;
elem=new Object[maxlen];
}
@Override
public void clear() {
top=-1;
}
@Override
public int length() {
return top+1;
}
@Override
public boolean full() {
return top>=maxlen-1;
}
@Override
public boolean empty() {
return top==-1;
}
//入栈元素e
@Override
public boolean pushs(Object e) {
if (full())
return false;
top++;
elem[top]=e;
return true;
}
//弹出一个元素
@Override
public Object pops() {
if(empty())
return null;
Object obj=elem[top];
top--;
return obj;
}
//获取栈顶元素
@Override
public Object getTop() {
if(empty())
return null;
Object obj=elem[top];
return obj;
}
//-----------------------测试顺序栈-------------------
public static void main(String[] args) {
SqStack stack = new SqStack(5);
stack.pushs(5);
stack.pushs(3);
System.out.println("当前出栈的元素为:"+stack.pops());
System.out.println("栈顶的元素为:"+stack.getTop());
System.out.println("栈是否为空"+stack.full());
}
}