C 程序进入infinte循环而不是调用函数?
我在练习一点链表,并试图将元素添加到排序的双链表中。然而,当我调用函数将元素添加到列表中时,程序将进入infinte循环,而不是调用函数。我已检查程序是否未进入函数,并在函数开始时添加打印语句。以下是整个计划:C 程序进入infinte循环而不是调用函数?,c,function,data-structures,linked-list,scanf,C,Function,Data Structures,Linked List,Scanf,我在练习一点链表,并试图将元素添加到排序的双链表中。然而,当我调用函数将元素添加到列表中时,程序将进入infinte循环,而不是调用函数。我已检查程序是否未进入函数,并在函数开始时添加打印语句。以下是整个计划: #include<stdio.h> #include<stdlib.h> struct node { int info; struct node* next; struct node* prev; }; struct node* sortedInser
#include<stdio.h>
#include<stdlib.h>
struct node
{
int info;
struct node* next;
struct node* prev;
};
struct node* sortedInsert(struct node* head, int data)
{
printf("x" );
struct node* res=head;
struct node* ptr=(struct node*)malloc(sizeof(struct node));
ptr->info=data;
ptr->next=NULL;
ptr->prev=NULL;
printf("X");
if(head==NULL)
return ptr;
else if(ptr->info<=head->info)
{
ptr->next=head;
head->prev=NULL;
res=ptr;
return res;
}
else
{
while(head!=NULL)
{
if(head->info>=ptr->info)
{
ptr->prev=head->prev;
ptr->next=head;
head->prev=ptr;
return res;
}
}
}
}
struct node* push(struct node* head)
{
struct node* ptr=(struct node*)malloc(sizeof(struct node));
int n;
printf("Enter size: ");
scanf("%d",&n);
printf("Enter elements: ");
for(int i=0;i<n;i++)
{
if(head==NULL)
{
scanf("%d",&ptr->info);
ptr->next=NULL;
ptr->prev=NULL;
head=ptr;
}
else
{
struct node* temp=(struct node*)malloc(sizeof(struct node));
scanf("%d",&temp->info);
temp->next=NULL;
temp->prev=ptr;
ptr->next=temp;
ptr=temp;
}
}
return head;
}
void display(struct node* head)
{
struct node *res;
for(res=head;res!=NULL;res=res->next)
printf("%d\t",res->info);
printf("\n");
}
int main()
{
struct node* head1=NULL;
head1=push(head1);
display(head1);
int num;
printf("Enter number: ");
scanf("%d",&num);
printf("%d\n",num);
head1=sortedInsert(head1,num);
display(head1);
return 0;
}
这是因为您没有将
头增加到while循环中的下一个节点
此外,在列表中找到要插入新节点的位置后,还需要使prev node指向新节点
head->prev->next=ptr代码>其他方面,您的列表将中断
您的代码应该如下所示
struct node* sortedInsert(struct node* head, int data)
{
.......
.......
while(head!=NULL)
{
if(head->info>=ptr->info)
{
ptr->prev=head->prev;
ptr->next=head;
head->prev->next = ptr; // to make prev node to point new node
head->prev=ptr;
return res;
}
head=head->next; // Increment the head to point next node.
}
.......
}
请不要发布输出的图片,将输出作为文本复制到问题中,并缩进4个空格,以便保留格式。图像非常浪费空间。显示的文本存储时间不应超过150字节,而发布的图像占用了77.13 KB(78980字节)
的存储空间。您添加了scanf
标记。您是否怀疑scanf
返回的结果是否正确?这似乎与你的问题毫不相干。
struct node* sortedInsert(struct node* head, int data)
{
.......
.......
while(head!=NULL)
{
if(head->info>=ptr->info)
{
ptr->prev=head->prev;
ptr->next=head;
head->prev->next = ptr; // to make prev node to point new node
head->prev=ptr;
return res;
}
head=head->next; // Increment the head to point next node.
}
.......
}