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