【问题标题】:Returning a pointer to the beginning of a linked list after adding nodes?添加节点后返回指向链表开头的指针?
【发布时间】:2016-11-29 04:06:14
【问题描述】:
struct node {
    struct node *next;
    int num;
} Node;


Node *insert(int i) {
    Node *head;
    for (int c = 0; c < i; c++) {
        head = malloc(sizeof(Node));
        head.num = i;
        head = head->next;
    }
}

插入函数应该创建一个链表并将从 0 到 i 的数字添加到该链表中。但是,它也应该返回一个指向列表开头/列表本身的指针,我似乎不知道该怎么做。在添加第一个节点后,我尝试创建一个指针并将其设置为等于 head,但它只返回第一个节点而不是整个列表。有人可以帮忙吗?谢谢。

【问题讨论】:

  • 你更大的问题是你没有为 head->next 分配任何值,所以你根本没有真正创建一个链表,只是一堆在空间中漂浮的节点跨度>
  • 我不确定我是否理解。因为我正在重新分配 head,所以 head->next 的 num 值不会是 1 吗?所以它会是一个 0->1->2->3.....->c 的链表,对吧?
  • 当您分配head = head-&gt;next; 时,您将在刚刚分配的指针上分配一个未初始化的指针。您泄漏了内存并存储了一个未定义的指针。你有很大的问题。该函数也应该返回一个值,但没有。

标签: c pointers linked-list


【解决方案1】:

您可能想记住前一个节点,以便分配它的下一个指针。添加节点时,将其 next 指针设置为旧的头,它现在成为列表的新头。您可以在循环的最后一次迭代后返回。

Node *insert(int i) {
    Node *head, *prev = NULL;
    for (int c = 0; c < i; c++) {
        head = malloc(sizeof(Node));
        head->num = i;
        head->next = prev;
        prev = head;
    }
    return head;
}

更新:要在列表末尾插入每个新元素,您需要更多的簿记:

Node *insert(int i) {
    Node *last_node = NULL;
    Node *first_node = NULL;
    for (int c = 0; c < i; c++) {
        Node *node = malloc(sizeof(Node));
        node->num = i;
        node->next = NULL;
        if (!last_node) {
            // Remember the first node, so we can return it.
            first_node = node;
        }
        else {
            // Otherwise, append to the existing list.
            last_node->next = node;
        }
        last_node = node;
    }
    return first_node;
}

【讨论】:

  • 这可行,但列表现在是从 i 到 0 而不是 0 到 i。有什么办法让它不会颠倒列表的顺序吗?
  • @P.Sate:是的,可以做到。你应该能够做到。您需要保留指向列表中最后一项以及第一项的指针。您将返回第一个,但在最后一个之后添加新项目。
【解决方案2】:

就像引入另一个变量一样简单。您当前有head 来跟踪列表的头部;添加另一个来跟踪列表的tail

struct node {
    struct node *next;
    int num;
} Node;

Node *insert(int i) {
    Node *head;
    Node *tail;
    head = malloc(sizeof(Node));
    head.num = 0;
    tail = head;
    for (int c = 1; c < i; c++) {
        // allocate a new node at the end of the list:
        tail->next = malloc(sizeof(Node));
        // set "tail" to point to the new tail node:
        tail = tail->next;
        tail->num = c;
    }

    return head;
}

如有必要,您还可以为 i == 0 添加特殊情况。

顺便说一句 - 我意识到这可能是作为练习给你的任务 - 但insert 对于一个实际上创建和填充一个全新列表的函数来说是一个糟糕的名字。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-22
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    • 2014-12-13
    • 1970-01-01
    相关资源
    最近更新 更多