2014-11-06 162 views
0

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

#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); 
} 
+0

关于架构的建议:让'insert'带一个'struct node *'并返回'struct node *';我发现这有点容易理解,因为你不必用双指针搞乱。 – APerson 2014-11-06 14:06:21

+1

您应该使用'%p'格式来打印指针或保留'%d'格式并打印节点数据。 – 2014-11-06 14:09:22

+2

@APerson:或者可能创建一个保持头部和尾部的列表结构,并使函数在指向该结构的指针上工作。 (返回新的头总是会产生一个冗余 - “head = something(head)” - 我发现比传递双指针更丑陋。) – 2014-11-06 14:13:40

回答

1

您还没有分配足够的内存

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

应该是:

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

然后一切工作正常。

+2

或'sizeof * newnode',毫无疑问,即将分配的内容与指定的指针类型。 [并在'malloc()']上丢失了这个强制类型(http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) – WhozCraig 2014-11-06 14:11:01