复制链接列表并返回指向新列表的指针 [英] Copying a linked list and returning a pointer to the new list
本文介绍了复制链接列表并返回指向新列表的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我当前的结构是:
typedef char AirportCode[4];
typedef struct node{
AirportCode airport;
struct node *next;
}Node;
我对函数应如何启动的想法是这样的:
My idea for how the function should start is this:
Node *copy(Node *list) {
int count = 0;
while (list != NULL){
count++;
list = list->next;
}
}
现在我们知道原始列表有多长时间,但之所以如此困惑,是因为我不知道如何为必须复制到第二个列表的每个单独节点分别分配内存.
Now we know how long the original list is, but the reason why I am so stumped is because I have no idea how to seperatly allocate the memory for each individual node that we have to copy to the second list.
推荐答案
我尚未测试过,但这应该可以完成工作:
I haven't tested it but this should do the job :
Node *copy(Node *list) {
int count = 0;
Node *previous = NULL ;
Node *firstnode = NULL ;
while (list != NULL){
Node *newnode = malloc(sizeof(node)) ;
if (firstnode == NULL)
firstnode = newnode ;
memcopy(newnode, list, sizeof(Node)) ;
newnode->next = NULL ;
if (previous != NULL)
previous->next = newnode ;
previous = newnode ;
count++;
list = list->next;
}
return firstnode ;
}
这篇关于复制链接列表并返回指向新列表的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文