【发布时间】:2020-02-02 12:52:09
【问题描述】:
-如果一个列表有整数数据如:1->2->3->4->5->6 -而pos_list有整数数据如:4->0->5 - 那么这个函数应该返回一个新列表,其中包含列表 A 中 pos_list 中给定位置的值 这样新列表= 5->1->6
我正在实施深层复制以创建新列表。 我正在尝试使用根据 pos_list 的数据进行迭代的循环。在这个循环中,A 的节点将移动到 pos_list 数据的位置。这次我将复制新列表中的节点 A 以创建另一个列表。 假设第一种情况,pos_list 有数据 4,所以循环将运行 4 次,直到列表 A 的节点指向它的第四个位置。在这个循环中,我将在一个新循环中复制列表 A 的数据。 我需要指导来解决这个问题。
struct node * sublist(struct node * A, struct node * pos_list) {
struct node* newList=NULL;
struct node * curr;
int i=0;
for (i = 0, curr = pos_list->next; (curr != NULL); curr = curr->next) { //pos_list->data has a dummy node so loop until the end of pos_list->data.
struct node* newList = (struct node *) malloc(sizeof (struct node));
for(int i=0;i<=pos_list->data;i++){ //counter for pos_list as it will be (3 then 0,6 and 4)
if(i==pos_list->data){ //At the time when i == pos_list->data(3 or 0 or 6..)
newList->data = A->data; //Putting value of list A data in new list.
newList = newList->next; //Linking
printf("%d\t", newList->data); //Just for log
}
A=A->next; //Going to next position on A
}
pos_list=pos_list->next; //Going to next position on B
}
return newList ;
}
如果一个列表是:1->2->3->4->5->6 而pos_list是:4->0->5
我希望输出是 5->1->6 的新列表
【问题讨论】:
-
总是用极端情况检查你的逻辑。如果你有一个空的 pos_list 怎么办?如果你有一个单元素 pos_list 怎么办?
-
这个问题需要一个 pos_list 数据来排列新列表,所以 pos_list 不可能为空。虽然空的 pos_list 可以是测试用例之一,但不会做任何安排。新列表的排列方式应使其包含列表 A 中 pos_list 中给定位置处出现的值。
-
空列表是包含零个元素的列表。除非您的作业明确说明“非空列表”,或者列表非空存在某些内在原因,否则任何列表都可能为空。在这个问题中没有这样的原因。一个空的 pos_list 只会导致一个空列表作为结果。这没有任何问题。
-
发布的代码不包含任何功能。它缺少
struct node的定义 -
Stackoverflow 不是来为您编写代码的。请发布minimal reproducible example,以便我们重现问题并帮助您调试。
标签: c algorithm linked-list singly-linked-list deep-copy