在双向链表的末尾插入节点

时间:2022-11-15 19:55:32

I tried inserting node at the end of doubly-linked list with a insert function but the process execution stops abruptly after second insertion. I tried checking out address of all pointer variable used in insert function and they show that my code works fine until the third insert function. How can I fix my code?

我尝试使用插入函数在双向链表的末尾插入节点,但是在第二次插入后进程执行突然停止。我试着检查插入函数中使用的所有指针变量的地址,它们表明我的代码工作正常,直到第三个插入函数。我该如何修复我的代码?

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

struct node {
    int data;
    struct node* next;
    struct node* prev;
};

void insert(struct node** header,int data) {
    struct node* newnode=(struct node*)malloc(sizeof(struct node*));
    newnode->data=data;
    newnode->prev=NULL;
    newnode->next=NULL;

    if(*header == NULL) {
        *header=newnode;
        return;
    }

    struct node* temp = *header;

    while(temp->next != NULL) {
        temp=temp->next;
    }

    temp->next = newnode;
    newnode->prev = temp;
    printf("%d\n**\n", temp->next);
}

void main() {
    struct node* head = NULL;
    insert(&head, 4);
    insert(&head, 45);
    printf("\n main head %d", head);
    insert(&head, 8);
    printf("testing");
    insert(&head, 69);
}

1 个解决方案

#1


1  

You are not allocating enough memory

你没有分配足够的内存

struct node* newnode=(struct node*)malloc(sizeof(struct node*)); 
// here you allocate only 4 bytes (or 8 bytes on a 64 bit system)

should be:

应该:

struct node* newnode = (struct node*)malloc(sizeof(struct node));

Then everything works fine.

一切正常。

#1


1  

You are not allocating enough memory

你没有分配足够的内存

struct node* newnode=(struct node*)malloc(sizeof(struct node*)); 
// here you allocate only 4 bytes (or 8 bytes on a 64 bit system)

should be:

应该:

struct node* newnode = (struct node*)malloc(sizeof(struct node));

Then everything works fine.

一切正常。