在c++中创建链表

Creation of linked list in c++

本文关键字:链表 创建 c++      更新时间:2023-10-16

我试图通过这个代码实现链表…我认为第一个节点被创建,它的数据,但指针指向下一个节点是不工作的第二次它说分割故障…请帮助

#include<cstdio>
#include<cstdlib>
struct node {
    int data;
    struct node *next;
};
struct node *root;
void append(int num)
{
    struct node *conductor;
    if (root == NULL) {
        root = new node;
        root->data = num;
        root->next = NULL;
        conductor = conductor->next;
    } else {
        conductor = root;
        while (conductor != NULL)
            conductor = conductor->next;
        conductor->next = new node;
        conductor = conductor->next;
        conductor->next = NULL;
        conductor->data = num;
    }
}
void display()
{
    struct node *conductor;
    conductor = root;
    while (conductor->next != NULL) {
        printf("%d->", conductor->data);
        conductor = conductor->next;
    }
    printf("%d->", conductor->data);
}
int main()
{
    int choice, num;
    while (1) {
        printf("Enter the choicen");
        scanf("%d", &choice);
        switch (choice) {
        case 1:
            scanf("%d", &num);
            append(num);
            break;
        case 2:
            display();
            break;
        case 3:
            exit(0);
        }
    }
    return (0);
}

正确代码:

#include<cstdio>
#include<cstdlib>
struct node {
    int data;
    struct node *next;
};
struct node *root;
void append(int num)
{
    struct node *conductor;
    if (root == NULL) {
        root = new node;
        root->data = num;
        root->next = NULL;
        // conductor = conductor->next; This was not needed at all.
    } else {
        conductor = root;
        while (conductor->next != NULL) // You were doing conductor != NULL
            conductor = conductor->next;
        conductor->next = new node;
        conductor = conductor->next;
        conductor->next = NULL;
        conductor->data = num;
    }
}
void display()
{
    struct node *conductor;
    conductor = root;
    if (conductor == NULL) return; // Returning if root is NULL
    while (conductor->next != NULL) {
        printf("%d->", conductor->data);
        conductor = conductor->next;
    }
    printf("%dn", conductor->data);
}
int main()
{
    int choice, num;
    while (1) {
        printf("Enter the choicen");
        scanf("%d", &choice);
        switch (choice) {
        case 1:
            scanf("%d", &num);
            append(num);
            break;
        case 2:
            display();
            break;
        case 3:
            exit(0);
        }
    }
    return (0);
}