0

我无法弄清楚我的插入功能有什么问题。

基本上在主函数中我要求用户输入一个整数,它应该遍历列表 RECURSIVELY 并按顺序插入数字。如果您需要其他任何东西,请告诉我。

当我打印出列表时,它只打印出 0 两次

In the main:
            **This is looped**
    printf("Enter the value you want to insert: ");
    scanf(" %d", &integer);
    current = insert(&head, integer);
    temp = current;

    while(temp)
    {
        printf("%d\n", temp->num);
        temp = temp->next;
    }


node* insert(node** head, int integer)
{
    node* temp = malloc(sizeof(node));
    node* temp1;
    node* new;

    if(*head == NULL)
    {
        temp->num = integer;
        temp->next = *head;
        *head = temp;
    }
    else if((*head)->num > integer)
    {
        temp = *head;
        temp1 = temp->next; //breaks the link
        temp->next = new;   //creates a new node
        new->num = integer;  //adds int
        new->next = temp1;   //links new node to previously broken node
        *head = temp;
    }

    else
        insert(&((*head)->next), integer);

    return(temp);
}

非常感谢!

4

2 回答 2

3
if(*head == NULL)
{
    (*head)->next == temp;
    temp->num = integer;
    temp->next = *head;
    *head = temp;
}

这是错误的,将导致无效读取,因为 *head 为 NULL,因此(*head)->next无效。它将从 读取NULL + offset。哪里offset取决于您的node数据类型的定义。

于 2013-03-18T11:31:52.997 回答
1
while(temp)
{
    printf("%d\n", current->num);
    temp = temp->next;
}

我想你想打印出来temp->num而不是current->num.

于 2013-03-18T11:36:13.633 回答