2015-03-19 178 views
-2

我在双向链表的末尾插入节点,但输出只显示第一个和最后一个元素。在双向链表中末尾插入

void insertend(int y) { 

    // y the element to be inserted<br> 
    // head is declared as global 

    node *ptr=(node*)malloc(sizeof(node)); 
    node *ptr1=head; 
    ptr->info=y; 

    if(head==NULL) { 
     ptr->next=ptr->prev=head; 
     head=ptr; 
    } 
    else { 

     ptr->prev=ptr1; 
     ptr->next=NULL; 
     ptr1->next=ptr; 
     ptr1=ptr; 
    } 

} 
void showtail() { 
    node *ptr=head; 
    while(ptr!=NULL) { 
     printf("%d\n",ptr->info); 
     ptr=ptr->next; 
    } 
} 

这里有什么问题?

+0

欢迎来到StackOverflow。请修复格式并向我们展示如何测试您的程序。 – Ilya 2015-03-19 05:03:56

+1

你可以运行一个调试器来解决这种怀疑 – sashas 2015-03-19 05:04:07

+1

,同时发布你的代码也显示你的结构 – Bhuvanesh 2015-03-19 05:20:21

回答

1

尝试...

if(head==NULL) 
{ 
    ptr->next=ptr->prev=head; 
    head=ptr; 
    } 
else 
{ 
    while(ptr1->next!=NULL) 
    ptr1=ptr1->next; 
    ptr->prev=ptr1; 
    ptr->next=NULL; 
    ptr1->next=ptr; 
    ptr1=ptr; 
    } 

你完全插入到最后一个节点之前遍历。否则,你必须保持ptr1作为静态变量。

1

当你试图在最后插入的DLL(或)元素SLL,需要traverse upto the end of the list

其他你需要保持上次插入节点的指针。

但是在这段代码中,您总是在第一个节点之后插入元素,这就是为什么您将第一个节点和最后一个节点作为输出。