将条目附加到链接列表的末尾

时间:2015-11-07 20:31:51

标签: c pointers linked-list

我想在最后添加一个链接列表的条目,但是在处理指针时遇到了麻烦。这是我的链接列表:

struct list {
    int val;
    list *next;
};

我在全球范围内声明了一个列表aList

struct list *aList;

并具有向列表中添加值的功能:

void add(int var) {
    struct list *temp = aList;
    if (temp == NULL) { //if aList is empty
        temp = malloc(sizeof(struct list));
        temp->val = var; //add it to first spot
        temp->next = NULL;
    } else { //if aList is not empty
        while (temp->next != NULL) { //find the first empty spot
            temp = temp->next;
        }
        temp = malloc(sizeof(struct list));
        temp->val = var; //add it to empty spot
        temp->next = NULL;
    }
}

我真的迷失了指针。我想添加到aList所以我需要创建一个指向它的临时列表并添加到它(任何更改都反映在aList上)。如果不使用临时列表,我将丢失列表的结构,它将包含1或0个元素,而不管我添加了多少。

我想要执行以下操作:

for (int i = 0; i < 5; i++) { add(i); }

我希望aList1->2->3->4->5->NULL,并且能够从1开始访问它。

1 个答案:

答案 0 :(得分:2)

while (temp->next != NULL) { //find the first empty spot
        temp = temp->next;
    }
    temp = malloc(sizeof(struct list));

当你这样做时,你会覆盖最后一个元素。

相反,您需要将其分配给新节点。

struct list *newnode = malloc(sizeof(struct list));
// Fill newnode
temp->next = newnode;