c - c - 链表中指针的问题

标签 c

这是我的代码(在链表上工作):

typedef struct node {
   int data;
   struct node_t* next;
} node_t;

typedef struct list{
   node_t* head;
} list_t;

node_t* create_node(void){
   node_t* tmp = malloc(sizeof(node_t));
   if (tmp == NULL){
      fprintf(stderr, "Error while allocating memory for node\n");
      exit(EXIT_FAILURE);
   }
   return tmp;
}

void list_insert(list_t* list, node_t* node, int data){
   if (node == NULL){
      node_t* new = create_node();
      new->next = list->head;
      list->head = new;
      new->data = data;
   }
   else{
      node_t* current = list->head;
      while(current != node){
         current = current->next;
      }
      node_t* new = create_node();
      new->next = current->next;
      current->next = new;
      new->data = data;
   }
}

我确实在 list_insert 函数中收到一些警告,但我无法弄清楚它们的原因。如果作为参数传递的 nodeNULL,则此函数应在开头插入一个新节点,否则应在 node 之后插入一个新节点> 作为参数传递。

在这段代码中:

if (node == NULL){
   node_t* new = create_node();
   new->next = list->head;
   list->head = new;
   new->data = data;
}

赋值 new->next = list->head; 不正确。有什么猜测吗?

最佳答案

在你定义的struct node中:

typedef struct node {
        int data;
        struct node_t* next;
    } node_t;

您将next 定义为指向struct node_t 的指针,但是没有这样的类型。你想要struct node:

typedef struct node {
        int data;
        struct node* next;
    } node_t;

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

相关文章:

从进程上下文计算 1 秒内的中断次数

python - 使用 ctypes 从 python 调用 darknet API(图像作为参数)

c++ - C/C++源代码可视化?

c - 传递 'swap' 的参数 1 使指针来自整数而不进行强制转换

c - gcc给linux ELF增加了哪些功能?

c - 求 1000 以下所有 3 或 5 的倍数之和

c++ - 分配和比较编码风格

c - c语言中的memset函数

c++ - 使用 C++ 以纳秒为单位提供时间的计时器功能

c++ - 用于 python 列表的 SWIG typemap to double *