c - 如何在已排序的链表中添加数字?

标签 c linked-list

我试图在 C 中创建一个函数来将数字添加到有序链表中,但我已经得到了 感觉它可以在更少的行中完成。有例子吗?

此示例代码不起作用:

#include <stdio.h>
#include <stdlib.h>

struct listNode {
    int number;
    struct listNode *nextPtr;
};

typedef struct listNode LISTNODE;
typedef LISTNODE *LISTNODEPTR;
int main ()
{
    LISTNODE a = {16,NULL};
    LISTNODEPTR ptr = &a;
    printList(&a);
    insert(&ptr,23);
    insert(&ptr,10);
    insert(&ptr,12);
    insert(&ptr,15);
    printList(&a);
    return 0;
}

void insert(LISTNODEPTR *list, int number){
    if((**list).number > number){
    printf("lol2 %d",number);
        LISTNODE *newNode =  malloc(sizeof(LISTNODE));
        (*newNode).number  = number;
        (*newNode).nextPtr  =  (*list);
        *list = newNode;
    }else if((**list).nextPtr == NULL){
    printf("lol %d",number);
        LISTNODE *newNode =  malloc(sizeof(LISTNODE));
        (*newNode).number  = number;
        (*newNode).nextPtr  =  NULL;
        (**list).nextPtr = newNode;

    }else{
    printf("other %d\n",number);
        LISTNODE *listPtr = *list;
        LISTNODE *listPtr1 = (*listPtr).nextPtr;
        while((*listPtr1).number < number && (*listPtr).nextPtr != NULL ){
            printf("%d > %d\n",(*listPtr).number , number);
            listPtr = (*listPtr).nextPtr;
            listPtr1 = (*listPtr).nextPtr;
        }
        LISTNODE *newNode =  malloc(sizeof(LISTNODE));
        (*newNode).number  = number;
        if((*listPtr).nextPtr != NULL){
            (*newNode).nextPtr  =  listPtr1;
        }else{
            (*newNode).nextPtr  =  NULL;
        }
        (*listPtr).nextPtr = newNode;
    }
}

最佳答案

是的,它可以做得更短:

void insert(LISTNODEPTR *list, int number)
{
    LISTNODE *newNode = malloc(sizeof *newNode);
    newNode->number = number;

    while (*list && (*list)->number < number)
    {
        list = &(*list)->nextPtr;
    }

    newNode->nextPtr = *list;
    *list = newNode;
}

另请注意,main 中的 printList 行应为 printList(ptr);

关于c - 如何在已排序的链表中添加数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2864924/

相关文章:

c - 使用队列进行基数排序

c - 我的链表代码有什么错误?

c - 算法 - 对 "n"输入文件进行排序并生成单个输出文件的最佳方法是什么

java - 在排序列表中递归插入、删除检索

java - 如何从文件中读取内容并按字母顺序将该文件的内容排序到链接列表中?

c - 意外的函数行为

java - hashmap java中的链表

c - C 中指向指针的指针抛出段错误

c - C 判断文件中是否包含字符串

c - 后台运行程序