Java棧——單鏈表實現
阿新 • • 發佈:2018-12-11
連結串列結構,用一個top指向連結串列棧頂,不需要其它的指標,當top指向為空時,棧為空
這個圖我畫的有點醜,大家將就看下
1.抽象介面
public interface Node {
//獲取節點資料域
public Object getData();
//設定節點資料域
public void setData(Object obj);
//刪除節點時起關鍵作用
public Node getNext();
}
public interface Stack { //棧大小 public int size(); //棧是否為空 public boolean isEmploy(); //入棧 public void push(Object e); //出棧 public Object pop() throws StackEmptyException; //棧頂元素 public Object peek() throws StackEmptyException; }
2.定義異常
/*
* 棧為空時,出棧或者取棧頂元素異常
*/
public class StackEmptyException extends RuntimeException{
public StackEmptyException(String err){
super(err);
}
}
3.實現介面
public class StackSLinked implements Stack{ //連結串列首節點使用 private SLNode top; //棧的大小 private int size; public StackSLinked(){ top = null; size = 0; } /* 返回棧的大小 */ public int size() { return size; } /* 判斷棧是否為空 */ public boolean isEmploy() { return size==0; } /* 入棧 */ public void push(Object e) { SLNode p = new SLNode(e,top); top = p; size++; } /* 出棧 */ public Object pop() throws StackEmptyException { if(size<1) throw new StackEmptyException("棧為空,GG"); Object obj = top.getData(); top = (SLNode) top.getNext(); size--; return obj; } /* 返回棧頂元素 */ public Object peek() throws StackEmptyException { if(size<1) throw new StackEmptyException("棧為空,GG"); return top.getData(); } }