无法在双链表中插入元素
Not able to insert the element in double 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;
}
谁能帮我解决这个问题?
您的 while 循环有问题。应该是:
while(k<pos && head!=NULL )
{
c = head;
head = head->next;
k++;
}
否则循环中只会执行第一条语句
我刚开始学习链表,我正在实现这个程序来将节点插入到双链表中。但是,即使在输入新节点的位置和数据后,我的程序仍继续接收输入。我整天都在思考这个问题,一直没能找出错误。这是代码:
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;
}
谁能帮我解决这个问题?
您的 while 循环有问题。应该是:
while(k<pos && head!=NULL )
{
c = head;
head = head->next;
k++;
}
否则循环中只会执行第一条语句