在c ++中创建链表

时间:2016-09-30 15:00:44

标签: c++ pointers data-structures

我正在尝试通过此代码实现链接列表...我认为第一个节点被创建并且它获取数据但指向下一个节点的指针第二次无法正常工作它表示分段错误...请帮助< / p>

#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 choice\n");
        scanf("%d", &choice);

        switch (choice) {
        case 1:
            scanf("%d", &num);
            append(num);
            break;
        case 2:
            display();
            break;
        case 3:
            exit(0);
        }
    }
    return (0);
}

1 个答案:

答案 0 :(得分: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("%d\n", conductor->data);
}

int main()
{
    int choice, num;

    while (1) {
        printf("Enter the choice\n");
        scanf("%d", &choice);

        switch (choice) {
        case 1:
            scanf("%d", &num);
            append(num);
            break;
        case 2:
            display();
            break;
        case 3:
            exit(0);
        }
    }
    return (0);
}