我正在尝试按升序将数字添加到链接列表中。我能解决什么问题呢?这是我的代码:

时间:2014-02-06 09:03:21

标签: c linked-list

此代码应按升序将数字放入链表中。这是我的程序的一个功能,它接受来自程序用户的键盘输入(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

2 个答案:

答案 0 :(得分:1)

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

head=insert(head,x);

您的Insert方法不返回任何内容(NULL)。所以你的头永远不会改变它总是为空;

return head;

只需在insert方法中返回head,它就能正常工作。

答案 1 :(得分:0)

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

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

}

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