我是编程的新手,所以我坚持使用这段代码。我正在尝试实现链表并应用评论中提到的功能。 当我调试程序时,它没有显示错误,但是当我运行代码时它说“控制台应用程序停止工作......” 我不知道这里有什么问题。为什么不起作用?
#include<iostream>
#include<conio.h>
using namespace std;
/*• InsertNodeAtFront()
• InsertNodeAtBack()
• PrintList()
*/
class list {
struct node {
int data;
node* next;
};
node *head;
node *current;
public:
list() {
head = NULL;
current = NULL;
}
void InsrtAtFront(int n) {
node *temp = new node;
temp->data = n;
temp->next = NULL;
if (head == NULL) {
temp = head;
}
else {
temp->next = head;
head = temp;
}
}
void InsrtAtBack(int a) {
node *temp1 = new node;
temp1->data = a;
temp1->next = NULL;
if (head == NULL) {
temp1 = head;
}
else {
current = head;
while (current->next!=NULL){
current = current->next;
}
current = temp1;
}
}
void print() {
current = head;
while (current->next != NULL) {
cout << current->data;
current = current->next;
}
}
};
void main() {
list obj1, obj2, obj3;
obj3.print();
obj1.InsrtAtFront(5);
obj1.InsrtAtFront(7);
obj1.InsrtAtFront(9);
obj3.print();
obj2.InsrtAtBack(2);
obj2.InsrtAtBack(4);
obj2.InsrtAtBack(6);
obj3.print();
}
答案 0 :(得分:0)
list() {
head = NULL;
current = NULL;
}
void print() {
current = head;
while (current->next != NULL) {
cout << current->data;
current = current->next;
}
}
//in main
list obj1, obj2, obj3;
obj3.print();
因此。你使用NULL引入头部,然后尝试使用当前头部的那个,并且它是null ..