将链表复制到C中的另一个列表

时间:2017-03-20 23:51:18

标签: c linked-list

有关于将链表复制到容器中的其他列表的问题。目前,我的代码是从全局列表中复制数据并将它们存储在临时列表中,并且数据存储在" student"容器的节点。但是,从该功能返回的结果在显示第一个学生后暂停程序。

我假设指针丢失参考?有人能够对此有所了解吗?自从我上次使用链表以来已经有好几年了。

当前输入:

汤姆

Jen

显示名字后,当前输出暂停:

我将此主题作为参考: C program to make a second copy of a linked list

struct container* list_by_name()
{   
    struct container *previous = NULL, *current = NULL;

    while (list != NULL) {      
        struct container *tempMainContainer = (struct container *) malloc(sizeof(struct container));
        struct student *tempStudentList = (struct student *) malloc(sizeof(struct student));

        // copy all students over to the list
        strcpy(tempStudentList->name, list->student->name);
        strcpy(tempStudentList->standard, list->student->standard);
        tempStudentList->absents = list->student->absents;

        // store student data into container
        tempMainContainer->student = tempStudentList;

        if (current == NULL) {
            current = tempMainContainer;
            previous = tempMainContainer;
        } else {
            previous->next = tempMainContainer;
            previous = tempMainContainer;
        }

        printf("%s\n", tempMainContainer->student->name);

        list = list->next;
    }

    // set container next to NULL
    current->next = NULL;

    return current;
}

1 个答案:

答案 0 :(得分:1)

我相信您遇到的问题是由于在方法结束时将current->next设置为NULL。

基本上,这一行:

current->next = NULL;

删除LL 中除之外的所有节点,添加第一个节点。

如果删除此行,则代码应按预期工作。

您的代码使用current来引用原始列表副本中的第一个节点。 current->next应该指向第二个节点,每个节点的下一个值应该指向它后面的节点。

您还希望将列表保存到临时变量,并在您的方法中迭代该临时变量 - 这样您就不会覆盖全局变量。

最后,您的方法将是:

struct container* list_by_name()
{

        struct container *previous = NULL, *current = NULL, *tmp = list;


        while (tmp != NULL) {
                struct container *tempMainContainer = (struct container *) malloc(sizeof(struct container));
                struct student *tempStudentList = (struct student *) malloc(sizeof(struct student));

                // copy all students over to the list
                strcpy(tempStudentList->name, tmp->student->name);
                strcpy(tempStudentList->standard, tmp->student->standard);
                tempStudentList->absents = tmp->student->absents;

                // store student data into container
                tempMainContainer->student = tempStudentList;
                tempMainContainer->next = NULL;

                if (current == NULL) {
                        current = tempMainContainer;
                        previous = tempMainContainer;
                } else {
                        previous->next = tempMainContainer;
                        previous = tempMainContainer;
                }

                printf("%s\n", tempMainContainer->student->name);

                tmp = tmp->next;
        }

        return current;
}
相关问题