1. 程式人生 > >Java棧的簡單實現

Java棧的簡單實現

元素 mys next() str stat 頭指針 出棧 push []

 * 數據結構與算法Java實現 棧
 * 
 * @author 小明
 *
 */
public class MyStack {
    private Node top;// 頭指針
    int size;// 長度

    public MyStack() {
        top = null;
        size = 0;
    }

    // 進棧函數
    public void push(Node node) {
        if (size == 0) {// 棧為空時
            top = node;
            size++;
        } 
else {// 棧不為空時 node.setNext(top); top=node; size++; } } //出棧函數 public void pop() throws IndexException { if(size==0) { throw new IndexException("索引錯誤!"); }else { top=top.getNext();//出棧 size--; } } @Override
public String toString() { String str=" "; Node temp=top; while(temp!=null){ str+=temp.getElement()+" "; temp=temp.getNext(); } str="["+str+" ]"; return str; } public static void main(String[] args) throws IndexException { MyStack mystack
=new MyStack(); mystack.push(new Node(0)); mystack.push(new Node(1)); mystack.push(new Node(2)); mystack.pop(); mystack.push(new Node(3)); System.out.println(mystack); } } class Node<T> { private T element;// 元素 private Node next;// 後繼 public Node(T element) {// 初始化函數 this.element = element; this.next = null; } public void setNext(Node node) { this.next = node; } public Node getNext() { return next; } public T getElement() { return element; } } /* * 索引異常類 */ class IndexException extends Exception { public IndexException() { } public IndexException(String s) { super(s); } }

Java棧的簡單實現