抱歉,标题不清楚,我真的不知道该怎么描述这个问题。我正在学计算机科学的第一年,所以我对C++还不太了解。然而,试图查找这一问题并没有帮助。
问题:在主要功能中,"printRawData“朋友函数被调用了两次。函数应该打印由类"LinkedList“存储的链接列表中的每个元素。它第一次工作,但第二次我得到一个分割错误。我真的不知道我做错了什么。我的T.A.说他认为结构的字符串变量"element_name“在被访问时被破坏了。
如果我没有很好地解释我的问题,或者如果我破坏了任何一种堆叠式的礼节,那么很抱歉我的代码太乱了。我很感激我得到的任何帮助。
//Note: C++ 11 is needed, due to to_string use
#include <iostream>
#include <string>
using namespace std;
struct Node {
string element_name;
int element_count;
Node* next;
};
class LinkedList{
private:
Node* first;
public:
LinkedList();
~LinkedList();
bool isEmpty();
void AddData(string name, int count);
friend void printRawData(LinkedList l);
};
//where the error occurs
void printRawData(LinkedList l){
Node* n = l.first;
while (n != NULL) { //iterates through the linked list and prints each element
cout << n->element_name << " : " << n->element_count << endl;
n = n->next;
}
}
LinkedList::LinkedList(){
first = NULL;
}
LinkedList::~LinkedList(){
Node* n = first;
while (n != NULL) {
Node* temp = n;
n = temp->next;
delete temp;
}
}
bool LinkedList::isEmpty(){
return first == NULL;
}
void LinkedList::AddData(string name, int count){
Node* newnode = new Node;
newnode->element_name = name;
newnode->element_count = count;
newnode->next = NULL;
Node* n = first;
//if the linked list is empty
if(n == NULL){
first = newnode;
return;
}
//if there's only one element in the linked list,
//if the name of first element comes before the name of new element,
//first element's pointer is to the new element.
//otherwise, the new node becomes the first and points to the previous first
//element.
if (n->next == NULL){
if (n->element_name < newnode->element_name){
n->next = newnode;
return;
} else {
newnode->next = first;
first = newnode;
return;
}
}
//if the first element's name comes after the new element's name,
//have the new element replace the first and point to it.
if (n->element_name > newnode->element_name){
newnode->next = first;
first = newnode;
return;
}
//iterating through linked list until the next element's name comes after
//the one we're inserting, then inserting before it.
while (n->next != NULL) {
if (n->next->element_name > newnode->element_name){
newnode->next = n->next;
n->next = newnode;
return;
}
n = n->next;
}
//since no element name in the linked list comes after the new element,
//the node is put at the back of the linked list
n->next = newnode;
}
main(){
LinkedList stack;
stack.AddData("Fish", 12);
stack.AddData("Dog", 18);
stack.AddData("Cat", 6);
printRawData(stack);
printRawData(stack);
}
发布于 2017-11-27 16:02:07
函数void printRawData(LinkedList l)
通过值传递参数,因此它获得LinkedList
对象的副本。
但是,副本包含first
指针的副本,但不复制任何节点。因此,当此副本被销毁时,LinkedList
析构函数将删除所有节点。
然后原版就被损坏了。
您可能希望传递一个引用,而不是创建一个副本。
这也是为什么std::list
有执行“深度复制”的复制构造函数和赋值操作符的原因,其中节点也被复制(不仅仅是列表头)。
https://stackoverflow.com/questions/47521747
复制