2014-08-31 101 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;