所以我有一个由随机生成的字符串组成的堆栈,然后是一个指向我的 .cpp 代码中下一项的指针。然后我检查并从堆栈中弹出每个项目并将它们打印出来。虽然最后我得到了一个段错误,所以我猜我正在尝试将一个项目弹出一个超出我不拥有内存的堆栈。
我相信我的复制构造函数不正确 - 也许它没有在我的堆栈中将最后一个值设置为 null 但我无法弄清楚为什么当我放行时它没有将值设置为 NULL
新上一个->下一个 = NULL;
这是我的代码(仅限班级)
#include <string>
using namespace std;
class Stack
{
protected:
struct Node
{
string item;
Node* next;
}; // struct Node
public:
// constructor of an empty stack
Stack ()
{
head = NULL;
}
// copy constructor
Stack( const Stack & rhs )
{
if (rhs.head == NULL) {// check whether original is empty
head = NULL;
}else{
head = new Node;
head->item = rhs.head->item;
Node* newPrev = head;
// Now, loop through the rest of the stack
for(Node* cur = rhs.head->next; cur != NULL; cur = cur->next)
{
newPrev->next = new Node;
newPrev = newPrev->next;
newPrev->item = cur->item;
} // end for
newPrev->next = NULL;
} // end else
}
// destructor
~Stack ()
{
delete head;
}
// assignment
const Stack & operator=( const Stack & rhs )
{
return *this;
}
// query whether the stack is empty
bool empty () const
{
return false;
}
// add an item to the top of the stack
// this method is complete and correct
void push (const string & new_item)
{
Node* new_node = new Node;
new_node->item = new_item;
new_node->next = head;
head = new_node;
}
// remove the item on the top of the stack
void pop ()
{
if (head!=NULL){
Node *n = head;
head = head->next;
delete n;
}
}
// return the item on the top of the stack, without modifying the stack
string & top () const
{
return head->item;
}
private:
Node* head;
};