ITPub博客

首页 > > > 自己用java实现了栈,

自己用java实现了栈,

作者:smanzheng 时间:2019-09-25 14:20:38 0 删除 编辑

自己用java实现了栈,但是pop()出来的数据不对,是跳着输出的(隔一个输出一个)

public class LinkedStackInnerImpl<T> {
    private class Node {
        T item;
        Node next;

        Node() {
            this.item = null;
            this.next = null;
        }

        Node(T item, Node next) {

            this.item = item;
            this.next = next;
        }

        boolean end() {
            return next == null && item == null;
        }

    }

    Node top = new Node();//哨兵

    public void push(T item) {
        top = new Node(item, top);
    }

    public T pop() {
        T result = top.item;
        if (!top.end()) {
            top = top.next;
        }
        return result;
    }

    public static void main(String[] args) {
        LinkedStackInnerImpl<String> linkedStackInner = new LinkedStackInnerImpl<>();
        for (String s : "123 1231 312 qwe ad z cxza sd zcd sdfse r ".split(" ")){
            linkedStackInner.push(s);
            System.out.print(s+" " );
        }
        System.out.println();
        while ( linkedStackInner.pop() != null){
            System.out.print(linkedStackInner.pop()+" ");
        }
    }

}

输出:

123 1231 312 qwe ad z cxza sd zcd sdfse r 
sdfse sd z qwe 1231 null


来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/4759/viewspace-3152286/ ,如需转载,请注明出处,否则将追究法律责任。

上一篇: direct2d c++
请登录后发表评论 登录
全部评论

注册时间:2019-04-25

  • 博文量
    115
  • 访问量
    1240