Wll_Knight

java实现链栈

package linkstack;

/**
 * Created by Administrator on 2019/4/18.
 */
public class LinkStack {

    private Element top;

    private Element base;

    class Element{
        public Object data;
        public Element next;
    }

    /**
     * 初始化栈
     */
    public void initStack(){
        top = new Element();
        base = new Element();
        top.next = base;
    }

    public void push(Object o){
        Element e = new Element();
        e.data = o;
        e.next = top.next;
        top.next = e;
    }

    public void pop(){
        if(top.next != base){
            System.out.println(top.next.data);
            top.next = top.next.next;
        }else {
            System.out.println("当前栈为空");
        }

    }

    public void print(){
        System.out.println("打印栈");
        Element e = top.next;
        while (e != base){
            System.out.println(e.data);
            e = e.next;
        }
    }

    @Override
    public String toString() {
        return "LinkStack{" +
                "top=" + top +
                ", base=" + base +
                '}';
    }
}

  

public static void main(String[] args){
        LinkStack linkStack = new LinkStack();
        linkStack.initStack();
        linkStack.push(1);
        linkStack.push(2);
        linkStack.push(3);
        linkStack.print();
        linkStack.pop();
        linkStack.print();
    }

  

posted on 2019-04-19 09:14  Wll_Knight  阅读(100)  评论(0编辑  收藏  举报

导航