首页 > 编程语言 > 详细

java实现链栈

时间:2019-04-19 10:05:26      阅读:171      评论:0      收藏:0      [点我收藏+]
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();
    }

  

java实现链栈

原文:https://www.cnblogs.com/wllknight/p/10733893.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!