简体   繁体   English

无法将元素插入双链表

[英]Not able to insert the element in double linked list

I have just started learning about linked lists and I was implementing this program to insert nodes into a double linked list. 我刚刚开始学习链表,并且正在实现该程序以将节点插入双链表。 However, my program keeps on taking input even after entering the position and data for the new node. 但是,即使在输入新节点的位置和数据之后,我的程序仍继续接受输入。 I have been pondering over this the whole day and haven't been able to figure out the mistake. 我整天都在琢磨这件事,却一直无法弄清错误。 Here's the code: 这是代码:

struct dll
{
  int data;
struct dll *next;
struct dll *prev;
};

void insert(struct dll *head, int data, int pos)
{
struct dll *a,*c;
int k=1;
a =(struct dll *)malloc(sizeof(struct dll ));


if(!a)
    printf("Memory error !");
else
{
    if(pos==1)
    {
        a->data=data;
        a->next = head;
        head->prev =a;
        head= a;
        a->prev =NULL;
        return;
    }
    else
    {
    a->data = data;
    while(k<pos && head!=NULL )
        c = head;
        head = head->next;
        k++;
}
    if(k!=pos){
   printf("Desired position doesn't exist !");
   return;
    }
  c->next = a;
a->prev = c;
a->next =head;
}

}

void display(struct dll *head)
{
while(head!=NULL)
{
    head = head->next;
    printf("%d",head->data);
}
}
 int main()
{
 int data, pos,i;
 struct dll *first,*header;
 first=(struct dll*)malloc(sizeof(struct dll));
 first->data =1;
 first->prev = NULL;
 first->next = NULL;
 header =first;

printf("Enter position !\n");

 scanf("%d",&pos);
  printf("Enter data !\n");
  scanf("%d",&data);
 insert(header,data,pos);

 display(header);
 return 0;
 }

Could anybody help me resolve the issue? 有人可以帮我解决问题吗?

You have a problem with your while loop. 您的while循环有问题。 It should be: 它应该是:

while(k<pos && head!=NULL )
{
    c = head;
    head = head->next;
    k++;
}

Otherwise only the first statement will be executed in the loop. 否则,将仅在循环中执行第一条语句。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM