我一直在尝试制作一个创建列表列表的程序(列表组包含两个列表: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;
}
您必须通过地址传递列表头(指针指向指针)或从函数返回新的列表头。我更喜欢前者,因为它可以让我从函数返回真正的错误代码,而不仅仅是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
}
试试这个:
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;
}