代码之家  ›  专栏  ›  技术社区  ›  Prachi Sharma

在java引用中使用LinkedList的堆栈实现工作不正常

  •  0
  • Prachi Sharma  · 技术社区  · 2 年前

    每次在此堆栈上调用push操作时,都会创建新节点,但堆栈只会变为null。 请帮我解决代码的问题。 我把参考变量搞砸了。当从main方法调用push操作时,top每次都会变为null。我不知道为什么会这样。 导入java。util。EmptyStackException;

    公共类LinkedListImplStack{

    public LinkedListImplStack() {
        this.top = null;
    }
    //Node
    private static class Node<T> {
        T data;
        Node next;
    
        public Node(T data) {
            this.data = data;
            this.next = null;
        }
    }
    
    // maintain top
    private Node top;
    
    //push()
    public void push(T data) {
        Node<T> node = new Node(data);
        node.next = top;
         top = node;
    }
    
    //pop()
    public T pop() {
        if(top == null)
            throw new EmptyStackException();
        T toBePopped = (T) top.data;
        top = top.next;
        return toBePopped;
    }
    
    //peek()
    public T peek() {
        if(top == null)
            throw new EmptyStackException();
        return (T) top.data;
    }
    
    @Override
    public String toString() {
        StringBuilder s = new StringBuilder();
        while(top!=null) {
            s.append(top.data + " -> ");
            top = top.next;
        }
        return s.toString();
    }
    public static void main(String[] args) {
        LinkedListImplStack myStack = new LinkedListImplStack();
        myStack.push(1);
        myStack.push(2);
        myStack.push(3);
        System.out.println(myStack);
        myStack.pop();
        System.out.println(myStack);
        myStack.push("four");
        System.out.println(myStack);
        System.out.println(myStack.peek());
    }
    

    }

    1 回复  |  直到 2 年前
        1
  •  1
  •   Ken Y-N    2 年前
    public String toString() {
        StringBuilder s = new StringBuilder();
        while(top!=null) {
            s.append(top.data + " -> ");
            top = top.next;
        }
        return s.toString();
    }
    

    打电话的时候 toString() ,则移动成员变量 top 有效地将指针指向堆栈的末尾 null 重新整理书堆;复印 顶部 然后反复迭代来解决你的问题。

        2
  •  0
  •   Prachi Sharma    2 年前

    在intellij中,有一个对象属性的enable-toString()视图,如果我们禁用它,那么只有在我们调用它时才会调用toString()。 否则,每次调用像stack这样的方法时都会调用toString()。正在调用push(),由于toString()方法的实现不正确,这会使堆栈为空。

    第一个答案将有助于理解。

    Skipped breakpoint because it happened inside debugger evaluation - Intellij IDEA