【问题标题】:Why does this pointer get assigned while copying a linked list?为什么在复制链表时会分配此指针?
【发布时间】:2014-11-16 04:29:39
【问题描述】:

在这段代码中:

Node *CopyList(Node **head) {
    Node *current = *head;
    Node *NewNode = NULL;
    Node *tail = NULL;

    while (current != NULL ) {
        if (NewNode == NULL) {
            NewNode = malloc(sizeof(Node));
            NewNode->data = current->data;
            NewNode->next = NULL; // routine
            tail = NewNode;
        } else {
            tail->next = malloc(sizeof(Node)); // here 
            tail = tail->next;
            tail->data = current->data;
            tail->next = NULL;
        }
        current = current->next;
    }
    return(NewNode);
}

为什么我们将tail->next 分配给malloc() 调用的结果?显然,如果我们不这样做,就会发生分段错误。

我们为什么不直接分配tail 而不是tail->next?什么情况下我应该这样分配?

【问题讨论】:

  • 这段代码看起来很合理。在第一次迭代中,它分配新列表的头部 (NewNode),在随后的每次迭代中,它扩展新列表的尾部。你认为这有什么问题?由于tail,不应该有段错误,因为它在使用时不会为NULL。这里唯一的错误是malloc 的返回值没有检查为NULL。
  • 我不认为这是错误的,只是我没有得到它的方式。

标签: c memory-management linked-list


【解决方案1】:

这只是为了方便,避免额外的变量:

Node* temp = malloc(sizeof(Node)); // here 
temp->data = current->data ;
temp->next = NULL ;

tail->next = temp ;
tail = tail->next;

为什么我们不只是分配 tail 而不是 tail->next ?

Tail 已经分配,​​它作为前一个节点,所以我们可以将它链接到下一个节点。我们分配一个新节点并将tail链接到该节点,tail->next = that_node。

【讨论】:

    【解决方案2】:

    这里NewNode代表新链表头。所以第一次在 while 循环中它被分配,所以下次它不会被改变。提出'tail->next'而不是'tail'的问题,因为第一次执行'Ne​​wNode == NULL'然后'tail = NewNode'意味着tail具有NewNode地址。所以接下来你需要将下一个块复制到'tail->next'中,因为tail已经有了'NewNode'。

    【讨论】:

    • 对不起,我还是不明白,我需要将下一个块复制到 'tail->next' 是什么意思,你能解释一下吗?跨度>
    • with in first if 'tail=NewNode' 意味着 NewNode 被分配给 tail。现在在其他部分,您应该将下一个块复制到尾部,这意味着您需要将新块分配给“tail->next”,因为尾部已经拥有 NewNode。一旦您通过采用具有超过 2 个节点的链表来尝试空运行。那你就轻松搞定了
    猜你喜欢
    • 1970-01-01
    • 2015-06-04
    • 2017-03-28
    • 2023-03-25
    • 2017-12-25
    • 1970-01-01
    • 2012-03-27
    • 1970-01-01
    • 2021-10-21
    相关资源
    最近更新 更多