【问题标题】:duplicating nodes of a single list in c在c中复制单个列表的节点
【发布时间】:2018-08-26 13:11:27
【问题描述】:

我有一个没有哨兵的非循环列表,我想复制它的每个节点。例如,我有 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);
 }

有人可以帮我吗?

【问题讨论】:

标签: c list pointers malloc nodes


【解决方案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);
 }

【讨论】:

  • 没有任何英文解释,你的回答对新手没有兴趣
  • 我的大部分 cmets 也适用于您的代码。此外:perror 会自动在提供的消息中添加:、空格和错误原因,因此在其中包含\n 可能最终看起来很难看。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-01
  • 1970-01-01
  • 2019-10-16
  • 2017-11-15
  • 1970-01-01
  • 2011-08-16
相关资源
最近更新 更多