开发者

Struct and Link List Question

I just learned how to use linked lists in C. Everything is okay if I use a single struct, but I am having problems when I use two structures to separate the data properly. I am having problems allocating. I am using Visual C++ Express 2010, and here's the entire code. Anyone could explain to me what went wrong? Thanks a lot. And this isn't homework. I am just trying to learn it further.

#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->nex开发者_开发问答t == NULL)
    {
        free(list);
    }
    else
    {
        destroyList(list->next);
        free(list);
    }
    printf("\n\nList has been destroyed.\n");
}


In createNode() you should set the next member to NULL; or even in append() if it makes you feel better :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜