此函数返回一个列表,其中包含出现在列表“ A”中“ pos_list”中给定位置的值

问题描述 投票:1回答:1

-如果列表具有整数数据,例如:1-> 2-> 3-> 4-> 5-> 6-并且pos_list具有整数数据,例如:4-> 0-> 5-然后此函数应返回一个New List帽子,其中包含出现在pos_list中给定位置的列表A中的值这样New List = 5-> 1-> 6

我正在实施深层复制以创建新列表。我正在尝试使用根据pos_list数据进行迭代的循环。在此循环内,A的节点将移动到pos_list数据的位置。这一次,我将在新列表中复制节点A,以创建另一个列表。对于第一种情况,pos_list具有数据4,因此循环将运行4次,直到list 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-> 6pos_list是:4-> 0-> 5

我希望输出是新列表,如5-> 1-> 6

c algorithm linked-list deep-copy
1个回答
0
投票

您的代码有几个问题:

© www.soinside.com 2019 - 2024. All rights reserved.