【发布时间】:2018-05-10 21:47:06
【问题描述】:
这是在主函数中。使用 Visual Studio 2017。
list a;
a.insertAtEnd("i", 1);
a.insertAtEnd("love", 1);
这里主要是在调用 end 的第二个插入时。程序崩溃并说 getnext() 为 NULL。即使在创建每个新节点时,next 指针都被声明为 NULL。
class node {
public:
node(string value) {
next = NULL;
data = value;
}
void setNext(node *temp) {
next = temp;
}
void setdata(string value) {
data = value;
}
node* getNext() {
return next;
}
调试器显示这个函数有问题^
string getData() {
return data;
}
void createDetail() {
detail *tmp = new detail();
d = tmp;
}
void setDetail(int lin) {
d->insertAtEnd(lin);
}
void getDetails() {
d->print();
}
private:
node *next;
string data;
detail *d;
};
class list {
public:
list() {
head = NULL;
}
void insertAtEnd(string, int);
void insertAfter(string, string);
void display();
private:
node *head;
};
void list::insertAtEnd(string value, int lin) { //main func being used
if (head == NULL) {
node *temp = new node(value);
temp->createDetail();
temp->setDetail(lin);
head = temp;
}
else {
node *temp2 = head;
while (temp2->getNext() != NULL || temp2->getData()!=value)
{
temp2 = temp2->getNext();
}
if (temp2->getData() == value)
{
temp2->setDetail(lin); //if same line then increment frequency, dont create new detail as word exists
}
else
{
node *temp = new node(value);
temp->createDetail();
temp->setDetail(lin);
temp2->setNext(temp);
}
}
}
【问题讨论】:
-
请发布完整的代码修复不必要的其他错误
-
剩下的代码很长。上面给出的是有问题的地方。
-
更具体地说,在while循环中...
-
你们俩都是对的。 minimal reproducible example 会很有帮助,错误在上面的代码中。
-
while (temp2->getNext() != NULL || temp2->getData()!=value)如果 getNext 为 NULL 但 getData 不是 == value 会发生什么?
标签: c++ list pointers hyperlink singly-linked-list