我知道所有代码都没有工作但是当我第一次运行程序并从文本字段读入第一个字符串时,程序错误输出。主要功能是将字符串传递给"插入列表功能"在实施中。 每次从文本文件中读入字符串时,程序都会插入一个节点。程序调用也调用我知道还没有工作的删除功能(这就是它被注释掉的原因)。我只是想找到调用insert函数时创建的错误。 main函数有一个while循环,它为每个文本条目创建一个Node,并逐个传递节点以按ABC顺序排序。
标题文件:
#include <string>
using namespace std;
struct Node
{
string data;
Node * next;
};
class List
{
public:
List();
~List();
bool Insert(string);
bool Delete(string);
void Print();
bool Edit(string, string);
private:
Node * head;
Node * cur;
Node * trailer;
};
实现:
#include <iostream>
#include <string>
#include <fstream>
#include "List.h"
using namespace std;
List::List():head(NULL)
{}
List::~List()
{}
bool List::Insert(string data)
{
Node* newNode = new Node;
if (newNode == NULL)
{
cout << "Error: Memory Allocation Failed" << endl;
return false;
}
newNode->data = data;
cur = head;
trailer = NULL;
if (head == NULL)
{
//cout << "head is Null" << endl;
head = newNode;
cout << head -> data << endl;
newNode->next = NULL;
//return true;
}
while (newNode->data > cur->data && cur -> next != NULL)
{
trailer = cur;
cur = cur->next;
}
if (cur->next == NULL)
{
cur->next = newNode;
newNode->next = NULL;
return true;
}
else
{
trailer->next = newNode;
newNode->next = cur;
return true;
}
}
bool List::Delete(string data)
{
/*Node *temp = head->next;
while (head != NULL)
{
delete head;
head = temp;
temp = head->next;
}
return true;*/
}
bool List::Edit(string dataDelete, string dataInsert)
{
Delete(dataDelete);
Insert(dataInsert);
return true;
}
void List::Print()
{
for (Node * Count = head; Count != NULL; Count = Count->next)
{
cout << Count->data << endl;
}
}
答案 0 :(得分:0)
插入第一个节点时,由于
而出现错误while (newNode->data > cur->data && cur -> next != NULL)
此时,cur中的值为NULL ,您正在尝试访问 cur-&gt;数据。
答案 1 :(得分:0)
@Deepak是对的,问题是当你插入第一个元素时head
变量是NULL
而cur
被设置为head
的值。< / p>
要修复它,您只需放置
即可cur = head;
trailer = NULL;
条件
之后if (head == NULL)
{
//cout << "head is Null" << endl;
head = newNode;
cout << head -> data << endl;
newNode->next = NULL;
//return true;
}
当您尝试插入应放在beggining中的元素(小于列表中任何其他值的值)时,也会出现错误。它会在循环条件
时发生trailer = NULL;
while (newNode->data > cur->data && cur -> next != NULL) { ... }
第一次通话中为false,因此trailer
将为NULL
。要修复它,您需要检查trailer
变量,如此
if (trailer == NULL) {
newNode->next = head;
head = newNode;
return true;
}
结果是Insert
的代码看起来像
bool List::Insert(string data)
{
Node* newNode = new Node;
if (newNode == NULL)
{
cout << "Error: Memory Allocation Failed" << endl;
return false;
}
newNode->data = data;
if (head == NULL)
{
head = newNode;
newNode->next = NULL;
return true;
}
cur = head;
trailer = NULL;
while (newNode->data > cur->data && cur -> next != NULL)
{
trailer = cur;
cur = cur->next;
}
if (trailer == NULL) {
newNode->next = head;
head = newNode;
return true;
}
if (cur->next == NULL)
{
cur->next = newNode;
newNode->next = NULL;
return true;
}
else
{
trailer->next = newNode;
newNode->next = cur;
return true;
}
}