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