在您的init() 函数中,您有点困惑如何在列表中添加开始节点。你有你的全局指针constant *head;当你添加一个节点时,你声明并分配一个新的临时节点并初始化成员设置attribute = data;和next = NULL;一旦你分配了你的第一个节点,你将节点地址分配给@ 987654325@.
不需要init() 函数,你真正需要的是一个add() 或push() 函数,它只是将数据作为参数传递,然后分配给节点,如上所述初始化,然后分配给列表中最后一个节点的next 指针。 (您也可以执行所谓的前向链接,每次都添加一个新的第一个节点,但列表中的节点最终与输入的顺序相反。
您可以使用两个全局指针head 和tail,其中tail 将始终指向列表中的最后一个节点。这样您就不必迭代插入到列表的末尾,只需在 tail->next = node; 添加新节点,然后更新 tail 使其指向新的结束节点,例如tail = node;
假设您的 struct constant 类似于:
typedef struct constant {
int attribute;
struct constant *next;
} constant;
您可以编写 add() 函数来处理将所有节点按顺序添加到列表中:
constant *head, *tail;
...
constant *add (int data)
{
constant *node = malloc (sizeof *node); /* allocate */
if (!node) { /* validate EVERY allocation */
perror ("malloc-node");
return NULL;
}
node->attribute = data; /* assign data to attribute */
node->next = NULL; /* initialize next NULL */
if (!head) /* if 1st node */
head = tail = node; /* assign node to both head, tail */
else { /* otherwise */
tail->next = node; /* set tail->next = node */
tail = node; /* update tail to point to last node */
}
return node; /* return pointer to added node to indicate success */
}
print() 和 free_list() 函数都可以简单地遍历每个节点,要么输出节点属性,要么释放节点。 free_list() 中唯一需要注意的是,您必须在删除当前节点之前递增到下一个节点。两个函数如下所示:
总而言之,你可以这样做:
#include <stdio.h>
#include <stdlib.h>
typedef struct constant {
int attribute;
struct constant *next;
} constant;
constant *head, *tail;
constant *add (int data)
{
constant *node = malloc (sizeof *node); /* allocate */
if (!node) { /* validate EVERY allocation */
perror ("malloc-node");
return NULL;
}
node->attribute = data; /* assign data to attribute */
node->next = NULL; /* initialize next NULL */
if (!head) /* if 1st node */
head = tail = node; /* assign node to both head, tail */
else { /* otherwise */
tail->next = node; /* set tail->next = node */
tail = node; /* update tail to point to last node */
}
return node; /* return pointer to added node to indicate success */
}
void prn_list (void)
{
/* loop over each node using iter and output attribute for each node */
for (constant *iter = head; iter; iter = iter->next)
printf (" %d", iter->attribute);
putchar ('\n');
}
void free_list (void)
{
/* loop over each node, but increment to next in list before deleting current */
for (constant *iter = head; iter;) {
constant *victim = iter;
iter = iter->next;
free (victim);
}
}
int main (void) {
for (int i = 0; i < 10; i++)
add (i + 1);
prn_list();
free_list();
}
使用/输出示例
$ ./bin/ll_global_head
1 2 3 4 5 6 7 8 9 10
查看一下,如果您还有其他问题,请告诉我。