c - 用 C 编辑列表程序

标签 c

我正在尝试编辑一年前制作的程序,但似乎我在某个地方失败了,因为我无法得到我想要的结果。我想让程序将数字从低到高排序,用户应该输入数字,直到按下 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/

相关文章:

c - 将混合类型参数作为指针传递给函数,我认为

c - 分配字符串数组的最快方法

C 编程 - 不计算值

python - 如何在python中使用struct/class的 vector

c - 子进程中的 SIGSEGV 信号处理

c - 如何从 C 程序为接口(interface)设置 ipv6 地址

在c中使用pthreads创建一个connection_handler(Linux/Windows)

c - libao : Playing blocks of audio as sequenze stutters

iphone - 在类之间共享结构信息 - Objective C - OpenGL ES

c++ - 当 b 不为零时,我总是有 `(a/b * b) + a % b == a` 吗?