将项目转换为C中链接列表的结尾 [英] Casting items to end of linked list in C

查看:176
本文介绍了将项目转换为C中链接列表的结尾的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

EDIT *(8:14 PM) - 对不起,我更正了我的代码,并改为一个方法,以便它可以更容易理解。

EDIT*(8:14 PM) - Sorry I corrected my code and made this instead a method so it can be more easily understood.

如何在添加到链表的末尾时正确转换结构体。编译这段代码给我一个强制警告在最后一行。这可能是为什么我的代码的其余部分无法正常工作的原因。

I am not sure how to properly cast a struct when adding to the end of a linked list. Compiling this code gives me an cast warning at the very last line. This may be the reason why the rest of my code does not properly function.

例如:

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


推荐答案


  • 确保包含stdlib.h - 需要使用malloc

  • 修复所有出现的wordNode为节点 - wordNode在您的程序中未定义

  • 为自我引用结构

  • 创建一个结构体和typedef,然后所有的警告消失; / p>

    and then all your warnings goes away;

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

    这篇关于将项目转换为C中链接列表的结尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆