这是你的数据结构:
struct node {
int factor;
struct node *next;
};
要在链表中创建一个新节点,调用这个函数并传递数据float factor和链表中的下一个元素struct node *next。该函数返回新节点。
创建一个新节点
#include <stdio.h>
#include <stdlib.h>
/* create new node */
struct node *new_node(float factor, struct node *next)
{
struct node *new = malloc(sizeof *new);
if (!new) {
fprintf(stderr, "Error: memory allocation failed\n");
exit(EXIT_FAILURE);
}
new->factor = factor;
new->next = next;
return new;
}
初始化(数组)链表
函数new_node可以这样调用:
/* first element in linked list */
struct node *head;
head = new_node(5.2, NULL);
/* add node to beginning of linked list */
head = new_node(3.7, head);
你可以像这样创建一个链表数组。数组的每个元素都包含一个链表的头部。
struct node lists[10];
for (int i = 0; i < 10; ++i)
lists[i] = new_node((float) i, NULL);
打印链表
如果要打印链表中包含的所有节点,请调用此函数print_nodes,并传递链表的第一个节点。
/* print the data contained in each node */
void print_nodes(struct node *head)
{
struct node *cursor = head;
while (cursor != NULL) {
printf("%f ", cursor->factor);
cursor = cursor->next;
}
printf("\n");
}
释放内存
记得在退出程序之前释放内存。您只需将链表的第一个元素传递给函数free_nodes。
/* free each node in linked list */
void free_nodes(struct node *head)
{
while (head != NULL) {
struct node *tmp = head;
head = head->next;
free(tmp);
}
}
要释放数组中每个链表的所有节点,您可以这样做:
for (int i = 0; i < 10; ++i)
free_nodes(lists[i]);