繁体   English   中英

我正在尝试按升序将数字添加到链接列表中。 我该如何解决才能正常工作? 这是我的代码:

[英]I'm trying to add numbers into a linked list in ascending order. what can I fix so it'll work? Here's my code:

此代码应按升序将数字放入链表中。 这是我程序的一项功能,该功能从程序用户处获取键盘输入(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()函数要求输入数字,然后将该输入发送到insert函数中,该函数应该将数字按升序排列。 样本输出:

$ 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);

您的Insert方法不返回任何内容(NULL)。 因此,您的头永不改变,始终为NULL;

return head;

只需将头返回insert方法,它将正常工作。

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

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

}

编辑:更正了代码,在复制时错过了条件检查

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM