C 学习链表

C 学习链表,c,linked-list,C,Linked List,我试图找出链表,我试图制作一个链表,每个节点中有2个项目,但我无法正确打印,我不确定我做错了什么 这是我的密码: #include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <string.h> struct node { int num; char word[30]; struct node *next; }; int main(void) {

我试图找出链表,我试图制作一个链表,每个节点中有2个项目,但我无法正确打印,我不确定我做错了什么

这是我的密码:

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>

struct node
{
    int num;
    char word[30];
    struct node *next;
};

int main(void)
{
    struct node *learn = NULL;
    struct node *temp;
    struct node *temp1, *p;
    int q, i = 0;
    char word1[30];

    while (i != 7)
    {
        printf("Enter a number: ");
        scanf("%d", &q);
        temp = (struct node *) malloc(sizeof(struct node));
        temp->num = q;
        temp->next = NULL;
        temp1 = p = learn;
        while (temp1 != NULL)
        {
            p = temp1;
            temp1 = temp1->next;
        }
        if (p != NULL)
            p->next = temp;
        else
            learn = temp;
        i++;
    }

    i = 0;
    while (i != 7)
    {
        if (i == 0)
        {
            int c;
            do
            {
                c = getchar();
            } while (c != '\n' && c != EOF);
        }
        printf("\nEnter a word: ");
        fgets(word1, 30, stdin);
        temp = (struct node*)malloc(sizeof(struct node));
        strcpy(temp->word, word1);
        temp->next = NULL;
        temp1 = p = learn;
        while (temp1 != NULL)
        {
            p = temp1;
            temp1 = temp1->next;
        }
        if (p != NULL)
            p->next = temp;
        else
            learn = temp;
        i++;

    }

    while (learn != NULL)
    {
        printf("%d\n", learn->num);
        learn = learn->next;
    }
    while (learn != NULL)
    {
        printf("%s", learn->word);
        learn = learn->next;
    }
}
输入一个单词:a

输入一个单词:b

输入一个单词:c

输入一个单词:d

输入一个单词:e

输入一个单词:f

输入一个单词:g

下面是我得到的:

1
2
3
4
5
6
7
0
0
0
0
0
0
0

我知道我做错了什么,我只是不知道是什么。

您为列表元素分配了两倍的内存。相反,您应该只分配一次,在第二个循环中,您应该使用strcpy或simillar添加字符串,或者您可以在同一个循环中读取数字和字符串。

底部的第一个while循环将遍历整个列表。“learn”在第一个while循环结束时为NULL,因此第二个循环从不打印任何内容

1
2
3
4
5
6
7
0
0
0
0
0
0
0