c - 在c中复制单个列表的节点

标签 c list pointers malloc nodes

我有一个没有哨兵的非循环列表,我想复制它的每个节点。例如,我有 7,5,12,16,我想要:7,7,5,5,12,12,16,16 但我无法创建它。下面是我复制节点的函数代码(程序的其他部分是正确的)。

    int duplicate_list(listT *list_head) {
    listT *current, *new_node;

    for(current = list_head; current != NULL; current = current->next,counter++) {
            new_node = (listT *)malloc(sizeof(listT));
            if(new_node == NULL) {
                printf("problem in new_node\n");
                free(new_node);
                exit(-1);
            }

            new_node->data = current->data;
            new_node->next = current;
    }
    return(1);
 }

有人可以帮助我吗?

最佳答案

您没有在列表中插入重复的 new_node,您只是在循环中创建新节点。请考虑以下示例供您引用。

    int duplicate_list(listT *list_head) {
    listT *current, *new_node;

    for(current = list_head; current != NULL; current = current->next,counter++) {
            new_node = malloc(sizeof(*new_node));
            if(new_node == NULL) {
                perror("problem in new_node");
                exit(1);
            }

            new_node->data = current->data;
            new_node->next = current->next;
            current->next = new_node;
            current = new_node;
    }
    return(1);
 }

关于c - 在c中复制单个列表的节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52026585/

相关文章:

c++ - 在 C/C++ 中编写 "pointer to something"的好方法

c - 有限状态机中的数组、指针和指向函数的指针

c - 如何在gdb中动态插入复杂输入

c - 将数据存储在列表 c 中

c - 如何在 Gstreamer 中修改音频流的播放速度?

java - 如何在 java 中列出一个 tar 文件的所有条目?

Python 3.2 空闲 : range function - print or list?

C++ - 指向函数内局部变量的指针

c# - C 和 C# 中的加法赋值?

c++ - gdb和ffmpeg编译