結點類java
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; } }