c - 双向链表程序运行时错误

标签 c

我对 C 语言编程经验不多。我不明白这段代码中的错误是什么。在将此代码放到网上之前,我已经尝试了 5 次。请帮忙。 我在这里实现了一个双向链表,它有两个函数可以将一个节点添加到列表中,另一个函数可以显示整个列表。编译成功后,如果我尝试添加一个节点,程序会意外结束。

#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
struct node
{
    int data;
    struct node* next;
    struct node* prev;
};
void display_list(struct node* ptr);    
void add_node(struct node* ptr)
{
    if(ptr->next==NULL)
    {
        ptr=(struct node*)malloc(sizeof(struct node));
        (ptr->next)->next=NULL;
        (ptr->next)->prev=ptr;
    }
    else        
    {   //traverse the list
        while(ptr->next!=NULL)
        {
            ptr=ptr->next;
        }
        (ptr->next)=(struct node*)malloc(sizeof(struct node));
        (ptr->next)->next=NULL;
        (ptr->next)->prev=ptr;
    }
    printf("\nEnter data : ");
    scanf("%d",((ptr->next)->data));
    display_list(ptr);
}
void display_list(struct node* ptr)
{
    if(ptr->next==NULL)
    {
        printf("%d\n",ptr->data);
    }
    else
    {
        //traverse the list and display each node
        while(ptr->next!=NULL)
        {
            printf("%d--->>>---",ptr->data);
            ptr=ptr->next;
        }
            //display last node
        printf("%d",ptr->data);
    }
}
int main()
{
    int choice;
    struct node* start=NULL;
    again:
    printf("\n1) Add node");
    printf("\n2) Display list");
    scanf("%d",&choice);
    if(choice==1)
        add_node(start);
    else if(choice==2)
        display_list(start);
    else 
        goto again;
    return 0;
}

最佳答案

在您的 add_node 函数中,您有一个 if 语句来检查 ptr->next 是否为 NULL ,但您实际上从未检查过 ptr itself 是否为 NULL

在你的 main 函数中,你可以看到第一次调用 add_node 时,参数确实是 NULL,因此第一个在该函数中,ptrNULL,一旦您的代码尝试检查 ptr->next,您就会遇到问题。


既然您在评论中提出了很好的问题,我将向您展示代码重构的含义。

现在,您的 add_node 实现将 struct node * 作为参数。问题是当你有这样的事情时:

struct node* ptr = NULL;
add_node(ptr);

即使您修改 add_node 以正确处理 NULL 参数,ptr 本身的值也不会更改一次 add_node 返回。一种方法是让 add_node 取而代之的是 struct node **。像这样:

void add_node(struct node ** head) {
    struct node * ptr = *head;

    // use ptr like you had before in the old implementation

    *head = ptr; // updating head.
                 // If ptr has changed, this will update head
                 // If it hasn't, then no harm
}

那样的话,如果你有类似的东西

struct node *foo;
add_node(&foo);

add_node 末尾的 *head = ptr 行将用正确的值更新变量,这次 foo < em>将在 add_node 返回时更新。

关于c - 双向链表程序运行时错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19342564/

相关文章:

python - Python 中的 8 Queens 解决方案

c - 字符串不按照分配方式打印

c++ - C 中的链表和 getifaddrs()

c - 无法将数组的引用传递给 C 中的方法

c# - 将字符串从 C# 传递到 C DLL

Java视频跨平台是一场噩梦,这有自由吗?

c++ - Linux 中是否有等同于 _set_pure call handler() 的函数?

c - 我的函数 "openfile"有什么问题

c - 用于将每个 c 源文件编译成 Linux 内核模块的 Makefile

c - 匿名结构指针