链式堆栈的实现

结点类

 

public class Node{
	
	Object element;  //数据元素
	Node next;       //表示下一下结点的对象引用
	
	Node(Object obj,Node nextval){   //用于其他结点的构造函数
		element = obj;
		next = nextval;
	}
	
	Node(Node nextval){       //用于头结点的构造函数
		next = nextval;
	}
	
	public Node getNext(){
		return next;
	}
	
	public void setNext(Node nextval){
		next = nextval;
	}
	
	public Object getElement(){
		return element;
	}
	
	public void setElement(Object obj){
		element = obj;
	}
	public String toString(){
		return element.toString();
	}
}

链式堆栈类

 

public class LinStack{
	
	Node head;     //堆栈头
	int size;      //结点个数
	
	public void LinStack(){    //构造函数
		head = null;
		size = 0;
	}
	
	public void push(Object obj){    //入栈
		head = new Node(obj, head);  //新结点作为新栈顶
		size ++;
	}
	
	public Object pop() throws Exception{     //出栈
		if(size == 0){
			throw new Exception("堆栈已空!");
		}
		Object obj = head.element;          //原栈顶数据元素
		head = head.next;                   //原栈顶结点脱链
		size --;
		return obj;
	}
	
	public boolean notEmpty(){            //非空否
		return head != null;
	}
	
	public Object getTop(){
		return head.element;
	}
}

 

 

 

你可能感兴趣的:(链式堆栈的实现)