【发布时间】: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