1.定义栈接口
package stack;
public interface Istack {
public void clear();
public boolean isEmpty();
public int length();
public Object peek();
public void push(Object x) throws Exception;
public Object pop();
}
2.定义Node结点
package stack;
import class2.Node;
public class Node {
private Object data;
private Node next;
//无参构造函数
public Node(){
// this(null,null);
this.data=null;
this.next=null;
}
//带一个参数的构造函数
public Node(Object data){
//this(data,null); //效果同下
this.data=data;
this.next=null;
}
//带两个参数的构造函数
public Node(Object data,Node next) {
this.data=data;
this.next=next;
}
//获取当前结点的数据
public Object getData(){
return data;
}
//获取当前结点的指针域
public Node getNext(){
return next;
}
//为当前结点赋值
public void setData(Object data){
this.data=data;
}
//修改当前结点的指针域
public void setNext(Node next){
this.next=next;
}
}
3.实现栈的接口,并定义链栈和方法
package stack;
public class Linkstack implements Istack{
private Node top;//只需声明即可
//清空链栈
public void clear(){
top=null;
}
//判断链栈是否为空
public boolean isEmpty(){
if(top==null)
return true;
else
return false;
}
//计算链栈的长度,时间复杂度为O(n)
public int length(){
int i=0;
while(top!=null){//与顺序栈不同,top指向链栈的栈顶元素
i++; //顺序栈top指向栈顶元素的下一个top=0,指向栈顶元素则为-1
top=top.getNext();
}
return i;
}
//返回链栈的栈顶元素
public Object peek(){
if(top!=null){
return top.getData();
}
else{
return null;
}
}
//做链栈的入栈操作
public void push(Object x) throws Exception{//先加入新结点,再移动top
Node p=new Node(x);//先构造新结点
p.setNext(top);//给结点设置下一个结点的索引
p=top;//移动top
}
//做链栈的出栈操作
public Object pop(){
if(top!=null){
Node p=top;//先取出结点,再移动top
top=top.getNext();
return p.getData();
}
else{
return null;
}
}
}