【问题标题】:Adding elements to linked list inside a linked list in C在C中的链表内将元素添加到链表
【发布时间】:2013-03-01 02:41:13
【问题描述】:

我正在尝试为主列表中的每个元素创建一个小列表。我的主列表工作正常,但我不知道如何访问小列表并将元素添加到小列表中。

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| using that pointer. I pass alongpointer->head` 到这个函数中。而且它不起作用。

insert(pointer->head, value)

【问题讨论】:

  • 了解如何通过按地址传递指针(即指向指针的指针)。

标签: c struct linked-list


【解决方案1】:

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

您当前设置的问题是您将指针->head 字段(恰好为空)的 value 传递给函数,而您想要改变的是存储在字段中。这是一个使用整数的程序,它说明了一个类似的错误:

void setFive(int i)
{
    i = 5;
}

int main(void)
{
    int myInt = 7;
    setFive(myInt);
    printf("%d\n", myInt); /* still 7! */
    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-16
    • 2017-09-09
    • 1970-01-01
    • 1970-01-01
    • 2020-09-13
    • 2017-02-25
    • 1970-01-01
    相关资源
    最近更新 更多