结构和链接列表问题

时间:2011-03-30 17:24:41

标签: c visual-c++

我刚刚学会了如何在C中使用链接列表。如果我使用单个结构,一切都没问题,但是当我使用两个结构来正确分离数据时,我遇到了问题。我在分配时遇到了问题。我正在使用Visual C ++ Express 2010,这是整个代码。任何人都可以向我解释出了什么问题?非常感谢。这不是功课。我只是想进一步学习它。

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

struct Student 
{
    char name[20];
    int num;

};

struct Node
{
    struct Student data;
    struct Node *next;
};


//void initList(struct Student **);
struct Node *createNode(struct Student );
void append(struct Node **, struct Student);
void traverse(struct Node *);
void destroyList(struct Node *);
int main()
{
    char choice = 'y';
    struct Student dat;
    struct Node *head;
    head = NULL;
    //struct Student *tmp;
    //initList(&head);
    char buff[20];
    while(choice != 'n')
    {
        scanf("%s %d", buff, &dat.num);
        strcpy(dat.name, buff);
        append(&head, dat);


        printf("\n\nWould you like to enter another?");
        fflush(stdin);
        scanf("%c", &choice);
    }

    traverse(head);
    destroyList(head);

    system("PAUSE");
    return 0;
}
/*
void initList(struct Student **list)
{
    *list = NULL;
}
*/
struct Node *createNode(struct Student dat)
{
    struct Node *temp;
    temp = (struct Node *)malloc(sizeof(Node));
    temp->data = dat;

    return temp;
}

void append(struct Node **pos, struct Student d)
{
    struct Node *node;
    node = createNode(d);

    if(*pos == NULL)
    {
        *pos = node;
    }
    else
    {
        struct Node *tmp;
        tmp = *pos;
        while(tmp->next != NULL)
        {
            tmp = tmp->next;
        }
        tmp->next = node;

    }
}

void traverse(struct Node *head)
{
    struct Node *tmp;
    for(tmp = head; tmp != NULL; tmp = tmp->next)
    {
        printf("\n %s %d\n\n", tmp->data.name, tmp->data.num);
    }

}
void destroyList(struct Node *list)
{
    if(list->next == NULL)
    {
        free(list);
    }
    else
    {
        destroyList(list->next);
        free(list);
    }
    printf("\n\nList has been destroyed.\n");
}

1 个答案:

答案 0 :(得分:4)

createNode()中,您应该将next成员设置为NULL;或者甚至在append()如果它让你感觉更好:)

相关问题