在双向链表中插入结尾

时间:2015-03-19 04:56:04

标签: c data-structures doubly-linked-list

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

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;
   }
}

这里有什么问题?

2 个答案:

答案 0 :(得分: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 :(得分:1)

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

否则你需要维护Last Inserted节点的指针。

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