【问题标题】:C++ - Stack with Linked List - Bad Memory Error?C++ - 带有链表的堆栈 - 内存错误?
【发布时间】:2011-05-04 05:52:20
【问题描述】:

我目前正在编写使用链表实现的堆栈。我收到此错误:

Unhandled exception at 0x75249617 in STACK_LinkedList.exe: Microsoft C++ exception: std::bad_alloc at memory location 0x002ee8f8. 

我相信它可能来自我的push()pop() 函数。我找不到我的错误。我对链表还很陌生,所以我很难找到错误。

这是我的push() 函数:

// Adds an item to the top of the stack
template <class S>
void Stack<S>::push(const S & e)
{
    NodePointer temp = new Node(e);

    if ( isEmpty() )
    {
        theTop = theFront = temp;
    }
    else
    {
            // Whatever is after top is stored in temp to keep track of it
        theTop->next = temp;

            // TheTop is stored in temp
        theTop = temp;  
        delete temp; 
    }
}

这是我的pop() 函数:

//Takes the item off the top of the stack
template <class S>
void Stack<S>::pop()
{
    if ( !isEmpty() )
    {        
                //temp node is set equal to the front
        NodePointer temp = theFront;

                //Holds the second to last node in the linked list
        NodePointer pred;

                //loops through until the node after temp is 0
        while (temp->next != 0)
        {
                        //sets the second to last as temp
            pred = temp ;

                        //basically "increments" temp to the next node
            temp = temp->next ;
        }

                //sets temp equal to the top
        temp = theTop;

                //the top is then set to its predecessor
        theTop = pred;

                //deletes what was known as the top
        delete temp;
    }

    else
        cout << "STACK IS EMPTY" << endl;

}

非常感谢!我相信我的大部分逻辑都是正确的。我只是缺少一些小东西。如果还有其他问题,请告诉我,我会发布该代码。

【问题讨论】:

  • 这是作业吗?如果是,将其标记为作业;如果没有,只需使用 STL :)
  • 从只有一个元素的堆栈中弹出一个元素后,theTop 的值是多少?提示:不为空。

标签: c++ stack linked-list


【解决方案1】:

您不应该在push 中删除您的temp!它是列表的一部分。因此,当您稍后访问这些数据时,您肯定会遇到异常。

其次,您必须在pop() 中使用NULL 初始化您的pred,否则如果堆栈仅包含一项,您将获得分配给theTop 的未定义值。

第三,你应该在pop()中删除你在push()中分配的Node。

总的来说,您的方法似乎不是很有效。您最好以其他方式存储指针:从堆栈顶部到底部项目。这样你就不需要遍历每个pop() 的整个堆栈。您的代码将是这样的:

void push(data)
{
    allocate new top
    new top's next is the old top
    store new top in the class
}

void pop()
{
    if empty, ERROR;
    new top = old top's next
    deallocate old top
}

请注意,您根本不需要 theFront

【讨论】:

  • 你太棒了,我的朋友……我意识到我之前做错了,但我已经用低效的方法做了。当我去修复它时,连同你的建议它奏效了。
【解决方案2】:

您的推送功能正在删除“temp”。但是, temp 指向您刚刚添加到列表中的数据。如果在指针上调用 delete,您并没有丢弃指针,而是删除它指向的内存!在 push 中删除你的 delete 语句并首先测试它(没有 pop)。我没有查看您的 pop 函数,但我会将其作为练习留给您在测试 pop() 后检查错误。

-Dan8080

【讨论】:

    猜你喜欢
    • 2011-09-16
    • 1970-01-01
    • 1970-01-01
    • 2014-12-13
    • 2021-09-22
    • 1970-01-01
    • 1970-01-01
    • 2012-10-25
    • 1970-01-01
    相关资源
    最近更新 更多