我試圖插入到一個雙向鏈表中。然後我嘗試在正向和反向上打印列表。我創建了一個頭節點,我試圖插入另一個節點,但我無法這樣做。該程序顯示運行時錯誤。 請在下面找到我的代碼。任何幫助,將不勝感激。在雙鏈表中插入
#include<stddef.h>
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
struct node *prev;
};
void insertAfter(struct node *node, int new_data){
if (node == NULL)
{
printf("the given previous node cannot be NULL");
return;
}
struct node* new_node = (struct node*)malloc(sizeof(struct node));
node->data = new_data;
node->next = new_node;
new_node->prev = node;
new_node->next - node->next;
if(new_node->next!=NULL)
new_node->next->prev = new_node;
}
void printlist(struct node *node){
struct node *last;
printf("Traversal in forward direction\n");
while(node!=NULL){
printf("%d\n",node->data);
last = node;
node=node->next;
}
printf("Traversal in backward direction\n");
while(last!=NULL){
printf("%d\n",last->data);
last=last->prev;
}
}
int main()
{
struct node *head;
struct node *tail;
head->data = 5;
tail->data = 10;
head->next = tail;
head->prev = NULL;
tail->next = NULL;
insertAfter(head, 8);
printf("\n Created DLL is: ");
printlist(head);
return 0;
}
請在您的問題中包含錯誤。 – carloabelli 2014-08-31 19:46:21
你沒有爲你的節點指針'* head'' * tail'分配內存。 – user1336087 2014-08-31 19:46:57