我无法在 C++ 中显示链表

I cannot display the linked list in c++

我有问题,我创建了一个新节点。 然后我创建了一个新节点,在开始时插入并显示它的显示。 然后我创建了另一个节点将它插入到最后但我无法在显示功能中显示它。 谁能告诉我这里有什么问题? 对于最终的链表,显示实际上没有出现。

代码如下:

#include<iostream>

using namespace std;
void createlinklist();
void insertatfirst();
void insertatend();
void display();
struct node {
    int data;
    node * link;
};
node * start = NULL;
node * location = NULL;
void createlinklist() {
    node * temp = new node;
    cout << "Enter data in first node";
    cin >> temp -> data;
    temp -> link = NULL;
    start = temp;
    location = temp;
}
void insertatfirst() {
    node * temp = new node;
    cout << "Enter data for new node at the beginning ";
    cin >> temp -> data;
    temp -> link = NULL;
    start = temp;
    temp -> link = location;

    location = start;
    cout << "Linked first after inserting data at is ";
    while (location != NULL) {
        cout << location -> data;
        location = location -> link;
    }
    location = temp;
}
void insertatend() {
    node * temp = new node;
    cout << "Enter data for new node at the end ";
    cin >> temp -> data;
    temp -> link = NULL;
    location = start;
    while (location != NULL) {
        location = location -> link;
    }
    location -> link = temp;
    location = temp;

}

void display() {
    location = start;
    while (location != NULL) {
        cout << "The final linked list after ending at last node is ";
        cout << location -> data;
        location = location -> link;

    }
}

int main() {

    createlinklist();
    insertatfirst();
    insertatend();
    display();

}

您的代码产生了分段错误,请查看这些代码行:

while (location != NULL) {
  location = location -> link;
}
location -> link = temp;
location = temp;

你是运行循环直到locationnull然后分配null -> link = temp(因为location已经是null)这个是导致分段错误的原因。

改变

while (location != NULL)

while (location -> link != NULL)

此后一切正常。