我正在尝试为主列表中的每个元素创建一个小列表。我的主列表工作正常,但我不知道如何访问小列表并将元素添加到小列表中。
struct smallList
{
char data;
struct smallList *next;
};
struct bigList
{
char data;
struct bigList *next;
struct smallList *head;
} *root;
当我向主列表添加内容时,我为每个新节点声明:
newNode->head = NULL;
我使用此函数来获取指向主列表中元素的当前指针:
struct bigList *pointer = getPointer(root, value);
然后,将内容添加到其 smallList| 中使用该指针。我将
pointer->head`传递给这个函数。而且它不起作用。
insert(pointer->head, value)
最佳答案
正如 WhozCraig 所建议的,您可以使用指向指针的指针来解决问题。像这样的事情:
void insert(struct smallList **head, char value)
{
*head = newSmallList(value, *head);
}
newSmallList
类似于:
struct smallList *newSmallList(char value, struct smallList *rest)
{
struct smallList *result = malloc(sizeof(struct smallList));
result->next = rest;
result->data = value;
return result;
}
当前设置的问题在于,您将指针->头字段(恰好为空)的值传递给函数,而您想要改变的是存储在字段中。这是一个使用整数的程序,它说明了类似的错误:
void setFive(int i)
{
i = 5;
}
int main(void)
{
int myInt = 7;
setFive(myInt);
printf("%d\n", myInt); /* still 7! */
return 0;
}
关于c - 在C中的链表内添加元素到链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15149568/