将条目附加到链表的末尾
Append entry to end of 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); }
我希望 aList
成为 1->2->3->4->5->NULL
并且能够从 1
开始访问它。
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;
我想在链表末尾添加一个条目,但在处理指针时遇到问题。这是我的链表:
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); }
我希望 aList
成为 1->2->3->4->5->NULL
并且能够从 1
开始访问它。
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;