c语言 - 我正在尝试按升序将数字添加到链表中。我可以修复什么才能正常工作?这是我的代码:



该代码应该按升序将数字放入链接列表中。这是我程序的一个函数,该函数从程序的用户中获取键盘输入(INT X)。

node* insert(node *head, int x)
{
    node *newPtr;
    node *prePtr;
    node *currentPtr;
    newPtr = malloc(sizeof(node));
    if(newPtr != NULL){
            newPtr->value = x;
            newPtr->next = NULL;
            prePtr = NULL;
            currentPtr = head;
            while(currentPtr != NULL && x > currentPtr->value){
                    prePtr = currentPtr;
                    currentPtr = currentPtr->next;
            }
            if(prePtr == NULL){
                    newPtr->next = head;
                    head = newPtr;
            }
            else{
                    prePtr->next = newPtr;
                    newPtr->next = currentPtr;
            }
    }
}
    int main(void)//calling input function in main
    {
        node *head = NULL;
        int x=0;
        while(x!=-1){
                printf("?: ");
                scanf("%d", &x);
                head=insert(head,x);
                print(head);
                printf("n");
        }
        return 0;
    }
//It seems to only put a few numbers in, then it resets

main()函数要求提供一个数值输入,并将输入发送到插入函数中,该函数应该以升序顺序排列数字。样本输出:

$ gcc prelab2.c
$ ./a.out
?: 4
4 -> NULL
?: 3
3 -> 4 -> NULL
?: 9
3 -> 4 -> 9 -> NULL
?: 7
3 -> 4 -> 7 -> 9 -> NULL
?: 2
2 -> 3 -> 4 -> 7 -> 9 -> NULL
?: -1

只有一个小错误。在main()方法中

head=insert(head,x);

您的插入方法不返回(null)。所以你的头永远不会改变它总是无效的;

return head;

只需在插入方法中返回头,它将正常工作。

尝试以下更改它应该可以正常工作。

node* insert(node *head, int x)
{
node *newPtr;
node *prePtr;
node *currentPtr;
newPtr = malloc(sizeof(node));
if(newPtr != NULL)
{
        newPtr->value = x;
        newPtr->next = NULL;
        // check if the linked list is empty add the node directly and return 
        if(head == NULL)
        {
            head = newptr;
            return head;
        }
        else 
        {
        currentPtr = head;
        while(x > currentPtr->value && currentPtr->next != NULL)
        {         
                currentPtr = currentPtr->next;
        }
             // make the new node point where current next is pointing
               newPtr->next = currentPtr->next;
             // make the current point to new node
               currentPtr->next = newPtr; 
        }
return head;
}
else
     return NULL; // signifying malloc failed
}

编辑:在复制

时,纠正了遗漏条件检查的代码

最新更新