小季不秃头 2022-10-16 18:48 采纳率: 66.7%
浏览 13
已结题

数据结构中双向链表中数据的插入

在写c语言中双向链表时,每当运行到输入函数都会报错,显示head是空指针。不知道到底错在哪,请各位指点指点。

#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
struct DoubleList {
    int element;
    struct DoubleList* next;
    struct DoubleList* prior;
};
typedef struct DoubleList* List;
void initDoubleList(List head)
{
    head->next = head->prior = NULL;
     
}
int insertDoubleList(List head, int element, int index) {
    if (index < 1)
        return 0;
    while (--index)
    {
        head = head->next;
        if (head == NULL)
            return 0;
    }
    List node = malloc(sizeof(struct DoubleList));
    if (node == NULL)
        return 0;
    node->element = element;
    
    if (head->next!=NULL)
    {
        head->next->prior = node;
        node->next = head->next;

    }
    else
    {
        node->next == NULL;

    }
    
    
    head->next = node;
    node->prior = head;
    return 1;
}
void print(List head)
{
    
    while (head)
    {
        head = head->next;
        printf("%d", head->element);

    }
}
int main()
{
    struct DoubleList head;
    initDoubleList(&head);
    for (int i = 1; i <= 3; i++)
        insertDoubleList(&head, i * 100, 1);
    
    print(&head);
    List node = &head;
    
    return 0;
}


  • 写回答

1条回答 默认 最新

  • Flashang_sg 2022-10-16 22:54
    关注

     發現兩個錯誤:

        } else {
            // Bug 1,不是 == 
            node->next = NULL;
        }
    
    
    void print(List head) {
        while (head) {
            head = head->next;
    
            // Bug 2,如果沒有這個,會宕機。
            if( head == NULL ) break;
    
            printf("%d \n", head->element);
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 10月25日
  • 已采纳回答 10月17日
  • 创建了问题 10月16日

悬赏问题

  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加
  • ¥15 用ns3仿真出5G核心网网元
  • ¥15 matlab答疑 关于海上风电的爬坡事件检测
  • ¥88 python部署量化回测异常问题
  • ¥30 酬劳2w元求合作写文章
  • ¥15 在现有系统基础上增加功能
  • ¥15 远程桌面文档内容复制粘贴,格式会变化