C++ - 链接列表堆栈 - 内存错误错误?

问题描述:

我目前正在编写使用链接列表实现的堆栈。我得到这个错误:C++ - 链接列表堆栈 - 内存错误错误?

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; 

} 

非常感谢!我相信我的大部分逻辑是正确的。我只是想念一些小事。如果是其他内容,请告诉我,我会发布该代码。

+2

这功课吗?如果是,将其标记为家庭作业;如果没有,只需使用STL :) – irrelephant 2010-11-02 23:58:56

+0

从一个堆栈中只有一个元素弹出一个元素之后,Top的值是多少?提示:不是null。 – 2010-11-03 00:00:51

你不应该删除pushtemp!这是列表的一部分。所以当你稍后访问这些数据时,你肯定会有一个例外。

其次,你必须在pop()NULL来初始化你pred,否则如果在堆栈中只有1个项目,你会得到分配给theTop一个未定义的值。

三,您应该在pop()中删除您在push()中分配的节点。

一般而言,您的方法似乎不是非常有效。你应该更好地存储指针:从栈顶到底部的项目。这样你就不需要遍历每个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可言。

+0

你真棒我的朋友... 我意识到我早些时候做错了这一点,但我已经做到了效率低下的方式。当我去解决这个问题的时候,随着你的建议一起工作。 – Johnrad 2010-11-03 01:58:36

+0

非常感谢! – Johnrad 2010-11-03 01:59:35

+0

不客气! – Vlad 2010-11-03 08:58:32

您的推送功能正在删除“temp”。但是,温度指向刚刚添加到列表中的数据。如果在指针上调用delete,你不会丢掉指针,而是删除它指向的内存!在推送和测试中摆脱您的删除语句(无弹出)。我没有看过你的弹出功能,但是我会把它作为练习让你在测试pop()后检查错误。

-Dan8080