2014-08-31 123 views
0

我試圖插入到一個雙向鏈表中。然後我嘗試在正向和反向上打印列表。我創建了一個頭節點,我試圖插入另一個節點,但我無法這樣做。該程序顯示運行時錯誤。 請在下面找到我的代碼。任何幫助,將不勝感激。在雙鏈表中插入

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

請在您的問題中包含錯誤。 – carloabelli 2014-08-31 19:46:21

+2

你沒有爲你的節點指針'* head'' * tail'分配內存。 – user1336087 2014-08-31 19:46:57

回答

1

這裏有幾個問題。

首先,正如@Igor指出的那樣,您沒有爲您的頭部和尾部節點分配任何內存。您還應該設置tail->prev = head

其次,insertAfter設置鏈接指針的順序導致node->next在用於設置new_node->next之前被覆蓋。這導致new_node->next指向new_node而不是跟隨node後面的任何內容。在修改node之前,您應該設置new_node->nextnew_node->prev。您也看到您在new_node->next的「分配」中使用了減號而不是等號。

第三,在printlist中,如果列表爲空,則應將last初始化爲NULL;否則,您將嘗試從未定義的開始(結束)點向後移動列表。

+0

這幫了我。非常感謝! :) – Weaver 2014-09-03 15:53:45

0

您需要爲您的指針頭部和尾部分配內存。

int main() 

    { 
     struct node *head; 
     struct node *tail; 
     head = malloc(sizeof(struct node)); //allocating memory to head 
     tail = malloc(sizeof(struct node)); //allocating memory to 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; 
    } 

另外,不要投malloc的返回值,因此改變:

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

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

+1

甚至'struct node * new_node = malloc(sizeof * new_node)' – pat 2014-08-31 20:00:45

+0

爲什麼'永遠不會投射malloc的返回值'?即使我這樣做,程序也能正常工作。 – Weaver 2014-09-03 15:55:12

+0

[我投出malloc的返回值?](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) – Igor 2014-09-03 17:27:40

0

你想new_node->next是一樣new_node

如果沒有,你最好換這兩行,在InsertAfter

node->next = new_node; 
new_node->next - node->next;