将项目转换为C中链接列表的末尾

编辑*(晚上8:14) – 抱歉,我更正了我的代码并将其作为一种方法,因此可以更容易理解。

在添加到链表的末尾时,我不确定如何正确地转换结构。 编译此代码会在最后一行给出一个强制警告。 这可能是我的其余代码无法正常运行的原因。

例如:

#include  typedef struct { int data; struct node *next; } node; node *HEAD = NULL; node *addNode(int num) { if (HEAD == NULL) { HEAD = (node *)malloc(sizeof(node)); HEAD->next = NULL; HEAD->data = num; } else { node *newNode; newNode = (node *)malloc(sizeof(node)); newNode->data = num; newNode->next = NULL; node *iter; iter = (node *)malloc(sizeof(node)); iter = (node *)HEAD; while(iter->next != NULL) iter = (node *)iter->next; iter->next = newNode; //warning : warning: assignment from incompatible pointer type } return HEAD; } 

  • 确保包含stdlib.h – 需要使用malloc
  • 将wordNode的所有出现修复为节点 – 在程序中未定义wordNode
  • 创建一个struct和typedef这两个命名节点 – 自引用结构的标准技巧

然后你所有的警告消失了;

 #include  struct node{ int data; struct node *next; }; typedef struct node node; node *HEAD = NULL; int main(int argc, char*argv[]) { int x = 1; int y = 2; if(HEAD == NULL) { HEAD = (node *)malloc(sizeof(node)); HEAD->next = NULL; HEAD->data = x; } else { node *newNode; newNode = (node *)malloc(sizeof(node)); newNode->data = y; newNode->next = NULL; node *iter; iter = (node *)malloc(sizeof(node)); iter = (node *)HEAD; while(iter->next != NULL) iter = (node *)iter->next; iter->next = newNode; //warning : warning: assignment from incompatible pointer type return 0; } } 

问题是在完全定义结构之前声明“next”是指向“struct node”的指针,因此“next”指向未定义的结构。 如果将“typedef struct {”更改为“typedef struct node {”,则该错误将消失。

您的代码存在许多问题。 第一个是转换malloc的返回值,并且不正确地引用要为其分配空间的类型的大小:

HEAD = (node *)malloc(sizeof(node));

应该被替换

HEAD = malloc(sizeof(*HEAD))

由于从void*到任何其他类型的转换始终在C中定义并隐式,因此您不会收到有关所需强制转换的任何警告。 指定sizeof(*HEAD)使编译器在编译时自动选择HEAD的类型,从而减少类型变化时所需的工作量。

您还应该记住,某些编译器不喜欢匿名结构(即没有声明名称的结构)。 因此,代码

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

应该被替换

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

其中声明了一个名为_node的结构,typedefed为名为node的类型。 并修复了循环引用。

最重要的是,你不需要为它提供malloc任何空间。