c - 递归/链表

标签 c recursion linked-list

我不知道我的插入函数有什么问题。

基本上在 main 函数中我要求用户输入一个整数,它应该递归地遍历列表并按顺序插入数字。如果您还需要什么,请告诉我。

当我打印出列表时,它只打印出 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);
}

非常感谢!

最佳答案

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

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

关于c - 递归/链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15475724/

相关文章:

c - 如何将任意大整数从 10 进制转换为 16 进制?

ruby - 有没有办法在不重新指定每个参数的情况下使用 ruby​​ 2 中的关键字参数进行递归?

android - android中迷宫生成的递归划分算法

java - 在java中使用递归从单个int参数获得多种输出

c - iPXE 如何在不调用函数名称的情况下执行函数

C:将 token 存储在不断增长的数组中

java - 无法从尾部到头部正确显示列表的节点

c++ - 返回链表C++中总数据的函数

c++ - 构建LinkedList时如何调整头尾指针

c - 使用for循环打印输出