c - 在c中复制单个列表的节点
问题描述
我有一个没有哨兵的非循环列表,我想复制它的每个节点。例如,我有 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);
}
推荐阅读
- android - Kotlin 内部列表过滤
- javascript - React:如何提交表单
- spartacus-storefront - 在最近发布的 Spartacus 中无法看到资源文件夹和 custom.property 文件
- angular - 如何在角度轮询期间保持过滤器完好无损?
- npm - npm 7 的 package-lock.json 中的“lockfileVersion: 2”是否与旧版本的 npm 兼容?
- c# - 如何读取正在发送的实际查询以及使用 NpgSql、c# 接收的数据?
- python - 从其他文件而不是 views.py 表单 DRF 向用户发送响应
- angular - 从 Azure Pipelines 中的 Azure 工件获取最新工件版本的最佳方式
- python - 尝试使用 lambda 从雅典娜视图获取数据时出现属性错误
- c# - 我有一个用 C# 编写的 Qr 生成器应用程序。所以现在我想生成在运行时每 10 秒改变一次的 Qr 代码