gpt4 book ai didi

将链表复制到另一个链表 - 迭代 - C - 理解返回的列表

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:44:47 25 4
gpt4 key购买 nike

尝试解决链表问题,今天我尝试“给定一个链表,将其复制到另一个链表”

为了迭代地执行此操作,

逻辑是- 使用三个指针 - current、newList、newTail。

current 跟踪给定原始列表中的当前节点

newList 以跟踪我要复制到的列表的head

Tail 以跟踪我正在复制到的列表的tail

  • 当新列表为空时,创建一个新节点并复制头部,总是有tail指向最后一个节点。

为此,我的复制列表函数应该看起来像这样 -

struct node* CopyList(struct node* head) {
struct node* current = head; // used to iterate over the original list
struct node* newList = NULL; // head of the new list
struct node* tail = NULL; // kept pointing to the last node in the new list

while (current != NULL) {
if (newList == NULL) { // special case for the first new node
newList = malloc(sizeof(struct node));
newList->data = current->data;
newList->next = NULL;
tail = newList;
}
else {
tail->next = malloc(sizeof(struct node));
tail = tail->next;
tail->data = current->data;
tail->next = NULL;
}
current = current->next;
}
return(newList);
}

我的问题是:如果我 return(newList) ,我将只有一个节点,不是吗?因为如果新列表不为空,我将推进 Tail,所以我不应该返回 Tail 而不是 newList 吗?

最佳答案

当您添加列表中的第一个元素时,newListtail 指向相同的地址 (tail = newList)。

每次添加另一个元素时,您都将其添加到 tail 之后,然后将其移动到下一个位置 (tail = tail->next)。也就是说,当您添加第二个元素时,tailnewList 现在将是 newList->next

这样,您可以返回 newList 并让所有指针指向列表中的下一个元素。

关于将链表复制到另一个链表 - 迭代 - C - 理解返回的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30491181/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com