无法在双链表

时间:2015-09-12 14:29:18

标签: c doubly-linked-list

我刚刚开始学习链表,我正在实现这个程序,将节点插入双链表。但是,即使在输入新节点的位置和数据后,我的程序仍继续输入。我整天都在思考这个问题,但却无法弄清楚这个错误。这是代码:

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

有人可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:1)

你的while循环有问题。它应该是:

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

否则只会在循环中执行第一个语句。