打印链表结构C.

时间:2015-12-18 22:44:41

标签: c list printing

所以,最近我不得不创建一个链表结构,我认为它有一个创建它的功能(希望如此),但现在我有一个简单的问题,如将它打印到控制台。我不知道我创建的结构是否有问题,或者我在打印时出错了。如果有人能找到我的代码有什么问题,我将不胜感激:

struct z { int a; struct z *next; };
struct z *head, *node, *next;
int data, x = 1;

int CreateList() {
    printf("Enter 0 to end\n");
    printf("Enter data no. %d: ", x);
    x++;
    scanf("%d", &data);
    if (data == 0) return 0;
    head = (struct z *)malloc(sizeof(struct z));
    if (head == NULL) { printf("Error creating head"); return 0; }
    node = head;
    node->a = data;
    node->next = NULL;
    while (data) {
        next = (struct z *)malloc(sizeof(struct z));
        if (next == NULL) { printf("Error creating next node no. %d", x); return 0;}
        node = next;
        printf("Enter data no. %d: ", x);
        x++;
        scanf("%d", &data);
        node->a = data;
        node->next = NULL;
    }
    return 0;
}


int main() {
    CreateList();
    node = head;
    while (node != NULL) {
        printf("%d ", node->a);
        node = node->next; //<=== crash on this line
    }
    return 0;
}

我的输出始终只是第一个输入的int,然后它在标记的行上全部崩溃。

2 个答案:

答案 0 :(得分:1)

您的main循环使用了错误的变量:

int main(){
    CreateList();
    node = head;
    while (next != NULL) {
        printf("%d ", node->a);
        node = node->next; //<=== crash on this line
    }
    return 0;
}

您应该使用node

int main(){
    CreateList();
    node = head;
    while (node != NULL) {
        printf("%d ", node->a);
        node = node->next; //<=== crash on this line
    }
    return 0;
}

顺便说一下,headnodenext应该是局部变量,而head应该由CreateList()返回。

CreateList()实际上并未正确创建列表:节点在创建时未链接到列表,只有第一个节点存储在head中。

以下是更正列表和相应main函数的更正版本:

struct z { int a; struct z *next; };

struct z *CreateList(void) {
    struct z *head, *node, *next;
    int data, x = 1;

    printf("Enter 0 to end\n");
    printf("Enter data no. %d: ", x);
    x++;
    if (scanf("%d", &data) != 1 || data == 0)
        return NULL;
    head = malloc(sizeof(struct z));
    if (head == NULL) {
        printf("Error creating head");
        return NULL;
    }
    node = head;
    node->a = data;
    node->next = NULL;
    for (;;) {
        printf("Enter data no. %d: ", x);
        x++;
        if (scanf("%d", &data) != 1 || data == 0)
            break;
        next = malloc(sizeof(struct z));
        if (next == NULL) {
            printf("Error creating next node no. %d", x - 1);
            return NULL;
        }
        node->next = next;
        node = next;
        node->a = data;
        node->next = NULL;
    }
    return head;
}

int main(void) {
    struct z *head = CreateList();
    struct z *node;
    for (node = head; node != NULL; node = node->next) {
        printf("%d ", node->a);
    }
    printf("\n");
    return 0;
}

答案 1 :(得分:0)

我认为你的问题是全局变量。在函数中创建它们,至少在节点和下一个节点中。当您实际添加值时,按需创建这些。作为最后一个提示,对于这种情况,一个do-while循环会使你的代码看起来比现在更清晰,绝对你有更少的代码重复。