我正在尝试编辑一年前制作的程序,但似乎我在某个地方失败了,因为我无法得到我想要的结果。我想让程序将数字从低到高排序,用户应该输入数字,直到按下 0。希望得到高级人士的帮助!
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
};
struct node* List;
void Add(struct node* p, int d)
{
struct node* q;
q = malloc(sizeof(struct node));
if (q == NULL)
printf("Not enaugh memory!");
else{
q->data = d;
if (List == NULL || List->data < d)
{
q->next = List;
List = q;
} else {
struct node *ptr = List;
while ((ptr->next != NULL) && (ptr->next->data>d)){
ptr = ptr->next;
}
q->next = ptr->next;
ptr->next = q;
}
}
}
int main()
{
int n, i, a;
printf("How many numbers are you going to enter? ");
scanf("%d", &n);
for (i = 1; i <= n; i++)
{
printf("\nEnter a number: ");
scanf("%d", &a);
Add(List, a);
}
printf("\nEntered and sorted numbers are: ");
struct node *ptr = List;
while (ptr != NULL)
{
printf("%d ", ptr->data);
ptr = ptr->next;
}
printf("\n\n");
system("PAUSE");
return 0;
}
最佳答案
只需更改行即可
if (List == NULL || List->data < d)
至
if (List == NULL || List->data > d)
并更改线路
while ((ptr->next != NULL) && (ptr->next->data>d)){
至
while ((ptr->next != NULL) && (ptr->next->data<d)){
而且您还没有添加0支票。请补充一下,休息一下就可以了。为此,请修改 for 循环:
//printf("How many numbers are you going to enter? ");
//scanf("%d", &n);
for (;;)
{
printf("\nEnter a number: ");
scanf("%d", &a);
if(a == 0)
break;
Add(List, a);
}
关于c - 用 C 编辑列表程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29375441/