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);
}
关于架构的建议:让'insert'带一个'struct node *'并返回'struct node *';我发现这有点容易理解,因为你不必用双指针搞乱。 – APerson 2014-11-06 14:06:21
您应该使用'%p'格式来打印指针或保留'%d'格式并打印节点数据。 – 2014-11-06 14:09:22
@APerson:或者可能创建一个保持头部和尾部的列表结构,并使函数在指向该结构的指针上工作。 (返回新的头总是会产生一个冗余 - “head = something(head)” - 我发现比传递双指针更丑陋。) – 2014-11-06 14:13:40