c - 链表——在末尾插入一个节点

标签 c data-structures linked-list

这段代码有什么问题。在插入操作过程中,当插入第二个元素时,程序停止运行,Windows 显示程序已停止工作。在构建日志中,它显示进程终止于状态 -1073741510,有时进程终止于状态 255。即使主函数中有一个 return 语句。

#include <stdio.h>
#include <conio.h>
#include <stdlib.h>

void insert(int);
void print();
struct node
{
    int data;
    struct node *link;
};
struct node *temp, *temp1, *temp2, *head, *end;
int main()
{
    int i, ch, a;

    head = NULL;
    temp = (node*)malloc(sizeof(node));
    printf("Enter the number of items");
    scanf("%d", &ch);
    for(i = 0; i < ch; i++)
    {
        printf("\nEnter the number");
        scanf("%d", &a);
        insert(a);
        **call to insert**
        print();
    }
    return 0;
}

void insert(int x)
{
    temp = (node*)malloc(sizeof(struct node));
    temp->data = x;
    temp->link = NULL;
    temp2 = head;
    if(head == NULL)
    {
        head = temp;
    }

    else
    {
        while(temp2 != NULL)
        {
            temp2 = temp2->link;
        }
        temp2->link = temp;
    }
}

void print()
{
    temp1 = head;
    printf("\nthe list is:");
    while(temp1 != NULL)
    {
        printf("%d", temp1->data);
        temp1 = temp1->link;
    }
}

最佳答案

这部分功能

else
{
    while(temp2 != NULL)
    {
        temp2 = temp2->link;
    }
    temp2->link = temp;
}

是错误的。退出循环后,节点 temp2 等于 NULL。因此这个声明

    temp2->link = temp;

导致未定义的行为。

按以下方式更改代码片段

else
{
    while(temp2->link != NULL)
    {
        temp2 = temp2->link;
    }
    temp2->link = temp;
}

main 中还有此语句

temp = (node*)malloc(sizeof(node));

没有意义并导致内存泄漏。

除了变量头之外的全局变量的声明

struct node *temp, *temp1, *temp2, *head, *end;

也没有道理。

关于c - 链表——在末尾插入一个节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44570660/

相关文章:

c++ - 链表,对将节点添加到列表头部的函数感到困惑

c - Linux 内核模块,防止 usbcore 在探测后注册另一个接口(interface)

java - 我可以使用什么数据结构或设计模式来解决这个问题

复制链表 - 使程序崩溃

c++ - 我需要帮助思考在 C 中实现 C++ 样式链表的不同方法

java - Java方法实现中的链表

c - 将非常量参数传递给需要 const 参数的函数时发出警告。有没有更好的办法?

c - 在 C 套接字中获取客户端的 IP 地址

c - 在 C 中使用 curl 未完成的下载

database - GAE Go 数据存储 - 忽略一些变量?