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

2019-01-02 23:10发布

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 

3条回答
趁早两清
2楼-- · 2019-01-02 23:20
 while ( linkedStackInner.pop() != null){  //pop 已经出栈了 
       System.out.print(linkedStackInner.pop()+" "); //又出一次
 }
查看更多
The star\"
3楼-- · 2019-01-02 23:32

每次执行linkedStackInner.pop()就是一次出栈,所以你可以设置个变量来存储这个值,而不是直接再调用一次这个方法

查看更多
孤傲高冷的网名
4楼-- · 2019-01-02 23:37

每执行一次linkedStackInner.pop()都是出栈一次

查看更多
登录 后发表回答