我的代码有什么问题?输出不显示

What is wrong with my code? The output doesn't show

本文关键字:输出 显示 问题 代码 什么 我的      更新时间:2023-10-16

我是编程新手,所以我被这段代码卡住了。我试图实现一个链表,并应用在评论中提到的功能。当我调试程序时,它没有显示任何错误,但是当我运行代码时,它说"控制台应用程序停止工作……"我不知道这是怎么回事。为什么它不起作用?

#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();
}
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初始化head然后试图使用while on current那是head那是NULL ..