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();
    }
}

猜你喜欢

转载自blog.csdn.net/qq_35561207/article/details/83031763