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

时间:2012-01-29 23:33:32

标签: c pointers casting struct linked-list

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

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

例如:

#include <stdlib.h>

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;
}

3 个答案:

答案 0 :(得分:1)

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

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

#include <stdlib.h>
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;
    }
}

答案 1 :(得分:0)

问题在于你声明&#34; next&#34;成为&#34; struct node&#34;的指针在结构完全定义之前,所以&#34; next&#34;指向未定义的结构。如果你改变&#34; typedef struct {&#34; to&#34; typedef struct node {&#34 ;,该错误将消失。

答案 2 :(得分:0)

您的代码存在许多问题。第一个是转换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不需要iter任何空格。

相关问题