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,但它只返回第一个节点,而不返回整个列表。有人可以帮忙吗?谢谢。
您可能想记住前一个节点,因此可以分配它的下一个指针。当您添加一个节点时,将其下一个指针设置为旧头,它现在成为列表的新头。您可以在循环的最后一次迭代后返回它。
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;
}
就像引入另一个变量一样简单。您当前可以使用
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
对于一个实际上创建并填充全新列表的函数来说是一个糟糕的名字。