这是我代码。
问题列表
1.如果我写“std::cout〈< this->first-〉new_data〈〈std::endl;“在函数void打印输出中,它会得到一个错误,你可以在我的代码中查看,我已经注解了它,但在while循环中,它可以显示输出,它正确,为什么???
2.我还没有连接到第一个节点,但输出是正确的。为什么??请帮助。
#include <iostream>
class Node { //this class create node
public:
int new_data = 0; //set default value
Node* next = nullptr;
};
class linked_list { //Create linked list
public:
Node *first; //represent the first node of linked list;
Node *last; //represent the last node of linked list;
linked_list() {// constructor assign default this value to NULL;
this->first = NULL;
this->last = new Node();
}
void pushback(int add_data); //create abstract class for write out side class;
void printout() { //show the values of linked list;
while (this->first != NULL) {
std::cout << this->first->new_data << std::endl;
this->first = this->first->next;
}
//std::cout << this->first->new_data << std::endl;<- this error/*Exception thrown: read access violation.this->first was nullptr.*/
//std::cout << this->last->data << std::endl;<- this work
}
};
void linked_list::pushback(int new_data) {//push from back function
if (this->first == NULL) { // if 1st node is NULL do this
Node* new_node = new Node(); /*create new_node assign value and connected to linked list*/
new_node->new_data = new_data;
new_node->next = NULL;
this->first = new_node;
this->last = new_node;
}
else {
Node* new_node = new Node(); /*create new_node assign value and connected to linked list*/
new_node->new_data = new_data;
new_node->next = this->last;
this->last->next = new_node;
this->last = new_node;
this->last->next = NULL;
}
}
int main()
{
linked_list a;
a.pushback(3);
a.pushback(9);
a.pushback(6);
a.pushback(66);
a.pushback(77);
a.pushback(99);
a.pushback(10000);
a.pushback(10001);
a.printout();
}
我希望有人解释给我,我会很高兴,如果你写了一个关于我如何可以修复它的示例代码。
1条答案
按热度按时间vs3odd8k1#
好了,现在我已经解决了这个问题。谢谢你的意见和建议。我已经研究了指针,我很明白。这是我的代码,我修复。它可能不是很好,但我认为它是最适合我现在。