【问题标题】:Linked list insert end node in C链表在C中插入结束节点
【发布时间】:2021-08-23 17:17:40
【问题描述】:

我目前正在学习 C 中的链表,并尝试编写一个函数以在末尾插入一个节点,然后打印所有数据。

一开始我的功能不起作用(只打印了1 2)

struct node {
    int data;
    struct node *link;
};

void add_end(struct node *head, int a){
    struct node *current, *temp;
    current = head;
    temp = (struct node*)malloc(sizeof(struct node));
    temp->data = a;
    temp->link = NULL;
    while(current != NULL){
        current = current->link;
    }
   current = temp;
};

int main()
{
struct node *head;
head = (struct node *)malloc(sizeof(struct node));
head->data = 1;
head->link = NULL;

struct node *current;
current = (struct node *)malloc(sizeof(struct node));
current->data = 2;
current->link = NULL;

head->link = current;

add_end(head, 3);

current = head;

while(current != NULL){
    printf("%d\n", current-> data);
    current = current->link;
    }

return 0;
}

修复一段时间后它工作了(打印了 1 2 3)

void add_end(struct node *head, int a){
    struct node *current, *temp;
    current = head;
    temp = (struct node*)malloc(sizeof(struct node));
    temp->data = a;
    temp->link = NULL;
    while(current->link != NULL){
        current = current->link;
    }
   current->link = temp;
};

谁能告诉我为什么第一个不起作用。我认为它们是相同的,因为在第一个版本中:current 是最后一个节点的链接,它是下一个节点(null)的地址,而在第二个版本中:current->link 是最后一个节点的链接,它也是下一个节点的地址(null)。

【问题讨论】:

  • 第一个不起作用,因为最终分配给current 绝对不会改变列表本身;它所做的只是改变局部变量current 指向的内容。之后,函数存在,分配的内存泄漏。第二个仅在head 引用函数初始节点时才有效。没有那个,它也不起作用(实际上会调用未定义的行为)。

标签: c linked-list


【解决方案1】:

一旦currentNULL,您已经传递了列表中的最后一个节点,而current 是一个NULL 指针。

分配给它不会将节点添加到列表中,它只会将current 重新分配为不再是NULL 指针,但最后一个节点link 不会被修改。

使用第二个函数,您可以找到列表中实际的最后一个节点,并将新节点附加到末尾。

【讨论】:

    猜你喜欢
    • 2019-04-26
    • 1970-01-01
    • 2022-01-20
    • 1970-01-01
    • 1970-01-01
    • 2011-08-13
    • 2015-10-20
    • 2018-07-28
    相关资源
    最近更新 更多