这是我复制列表的功能。错误是它总是复制第一个元素两次。我究竟做错了什么?
Node *copy(Node *list) {
Node *newlist, *p;
p = malloc(sizeof(Node));
newlist = p;
while (list != NULL) {
strcpy(p->airport, list->airport);
p = p->next;
p = malloc(sizeof(Node));
list = list->next;
}
return newlist;
}
最佳答案
将其分成 3 个部分。
// Part 1 - the null list
if (list == NULL) return NULL;
// Part 2 - the head element
Node *newHead = malloc(sizeof(Node));
strcpy(newHead->airport, list->airport);
// Part 3 - the rest of the list
Node *p = newHead;
list = list->next;
while(list != NULL) {
p->next = malloc(sizeof(Node);
p=p->next;
strcpy(p->airport, list->airport);
list = list->next;
}
p->next = NULL; // terminate last element.
关于c - 如何在 C 中复制链表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22235203/