为什么我的函数在堆栈中存储数据时不返回堆栈(自制的堆栈类)?

rt4zxlrg  于 2021-07-06  发布在  Java
关注(0)|答案(2)|浏览(336)

我试图首先用java将数据保存在自制的堆栈数据结构的对象中。但问题是,当我想返回该堆栈以便在另一个可以使用该堆栈的函数中重用时,它会返回一个空堆栈。然而,就在前一行,我已经打印了所有堆栈元素,它不是空的。代码如下:

public Stack allLeafNodes(TreeNode root)
{
    Stack stack= new Stack();
    if (root == null)
        return null;
    if (root.getLeft() == null &&
            root.getRight() == null)
    {
        stack.push(root.getData());
    }
    if (root.getLeft() != null)
        allLeafNodes(root.getLeft());
    if (root.getRight() != null)
        allLeafNodes(root.getRight());
    else{
        stack.print(); // at this call all elements are getting printed
        return stack; //but when it returns, the stack is empty
    }
    return stack;
}
mwyxok5s

mwyxok5s1#

我认为在你的 print() 你使用的方法 pop() 方法。就其本身而言,这种行为是正常的。来自javadoc pop() ```
Removes the object at the top of this stack and returns that object as the value of this function.

不管怎样,你的方法 `print()` 清理你的堆。
hs1rzwqc

hs1rzwqc2#

你好像用了一些自定义类 Stack (不是 java.util.Stack )方法的自定义实现 print 可能是用 pop() 从而从堆栈中删除所有元素的操作。
因此,方法 print() 需要修改;也许值得重写 Stack 的方法 toString() 确保堆栈内容未被修改,并将其用于调试打印。

相关问题