C上的链表返回NULL

时间:2014-05-31 03:19:09

标签: c list struct insert linked-list

我一直在尝试创建一个创建列表列表的程序(列表包含两个列表:transform和obj。所有代码都已完成,但是当我尝试打印列表的元素时,我得到一个NULL。我想问题是在列表的节点之间的链接。下面,将转换(或对象,语法相同)插入转换列表和插入组的函数的函数到主列表。有什么建议吗?

void insertTransform (Transform* transform, char *command, char *command2)
{
     Transform * newTransform = (Transform*) malloc(sizeof(Transform));
     newTransform->k = findKey(command);
     newTransform->ttype = command;
     newTransform->param = command2;
     if (transform==NULL)
     {
         transform=newTransform;
         transform->next=NULL;
     }
     else
     {
         newTransform->next=transform;
         transform=newTransform;
     }
}

void insertGroup (Group* group, Transform *transform, Obj *obj)
{
     Group * newGroup = (Group*) malloc(sizeof(Group));
     newGroup->t = transform;
     newGroup->obj = obj;
     newGroup->next=group;
     group=newGroup;
}

2 个答案:

答案 0 :(得分:0)

试试这个:

void insertGroup (Group* group, Transform *transform, Obj *obj)
{
     Group * newGroup = (Group*) malloc(sizeof(Group));
     newGroup->t = transform;
     newGroup->obj = obj;
     newGroup->next=NULL;
     group->next=newGroup;
}

这假定传入的组是当前头,并且您尝试在最后添加新节点。

或者在开头插入:

void insertGroup (Group* group, Transform *transform, Obj *obj)
{
     Group * newGroup = (Group*) malloc(sizeof(Group));
     newGroup->t = transform;
     newGroup->obj = obj;
     newGroup->next= group->next;
     group->next=newGroup;
}

答案 1 :(得分:0)

您必须按地址(指向指针的指针)传递列表,或者从函数返回新的列表头。我更喜欢前者,因为它让我从函数中返回真正的错误代码,而不仅仅是NULL。

以相反的顺序处理这些:

int insertGroup (Group** group, Transform *transform, Obj *obj)
{
     Group * newGroup = malloc(sizeof(Group));
     if (newGroup == NULL)
     {
         perror("Failed to allocate new group");
         return -1;
     }

     newGroup->t = transform;
     newGroup->obj = obj;
     newGroup->next=*group;
     *group=newGroup;
     return 0;
}

调用

Group *grp = NULL;
if (insertGroup(&grp, transform, obj) != 0)
{
     // error condition
}

变换同样处理:

int insertTransform (Transform** transform, char *command, char *command2)
{
     Transform * newTransform = malloc(sizeof(Transform));
     if (newTransform == NULL)
     {
         perror("Failed to allocate new transform");
         return -1;
     }

     newTransform->k = findKey(command);
     newTransform->ttype = command;
     newTransform->param = command2;
     newTransform->next = *transform;
     *transform = newTransform;
     return 0;
}

再次,调用为:

Transform *tfrm = NULL;
if (insertTransform(&tfrm, cmd1, cmd2) != 0)
{
    // error condition
}

希望能让你前进。