C ++中基于链接的堆栈

时间:2019-03-19 02:40:37

标签: c++ data-structures

我一直试图弄清楚如何创建基于链接的堆栈,并遇到了一段我不太了解的代码片段。

int pop()
{
    // If the stack is empty return a sentinel value
    if (isEmpty())
        return -999;

    // Get the data to return from the top of the stack
    int intReturn = top->info;

    // Create a pointer to keep track of the top node
    IntSLLNode *temp;
    temp = top;

    // Move the top of the stack to the next element
    // or null if there is no next element
    top = top->next;

    // Free up memory
    delete temp;

    // Send back the data
    return intReturn;
    ...
}

直到top=top->next我都了解。

1)如果我们从未真正使用过临时节点,那么创建临时节点有什么意义呢?

2)通过将顶部指针移动到下一个节点,我们是否要删除前一个顶部节点?这样弹出吗?

谢谢

1 个答案:

答案 0 :(得分:1)

1)之所以需要temp,是因为在移动top之后,我们需要旧的top值,以释放正在弹出的节点的内存。我们必须移动top然后释放内存;如果我们尝试以另一种方式(释放内存,然后移动top)来执行此操作,那么我们将不得不使用一个临时变量来保存top->next(因为在这种情况下这会丢失)。无论哪种情况,都无法避免使用临时变量。

2)移动top导致将第二个节点提升为顶部节点,并从堆栈中删除顶部节点(这是我们对pop的期望的一半,另一半正在返回弹出节点的值)。直到delete temp才删除该节点,这就是为什么我们需要保留它。