1. 程式人生 > >java之---實現資料結構--棧(基本版)

java之---實現資料結構--棧(基本版)

package 資料結構;

/**
 * java程式碼實現棧
 */
 class stack {
    private class Data {
        private Object obj;
        private Data next = null;

        Data(Object obj) {
            this.obj = obj;
        }
    }

    private Data first = null;

    public void insert(Object obj) {
        Data data = new Data(obj);//將取得的值賦值給棧底
        data.next = first;//因為first為null,將data.next的下一個值賦值為null,每次插入一下,呼叫一次該方法。
        first = data;
    }

    public Object delete() throws Exception {
        if (first == null) throw new Exception("empty");
        Data temp = first;
        first = first.next;
        return temp.obj;
    }

    public void display() {
        if (first == null) {
            System.out.println("empty");
        }
        System.out.println("top -> bottom:|");
        Data current = first;
        while (current != null) {
            System.out.println(current.obj.toString() + "|");
            current = current.next;
        }
        System.out.println("\n");
    }
}

public class stacktest {
    private stack ss=new stack();
    public void push(Object obj){
        ss.insert(obj);//呼叫具體實現類所定義的插入方法
    }
    public Object pop()throws Exception{
        return ss.delete();
    }
    public void dispaly(){
        ss.display();
    }
    public static void main(String[] args)throws Exception {
     stacktest  hss=new stacktest();
         hss.push(1);//將1放入棧中
         hss.push(2);
         hss.push(3);
         hss.push(4);
         hss.dispaly();
         System.out.println(hss.pop());
         hss.dispaly();
    }
}