基于给定的结构在C中创建一个链表数组



我需要通过在C.中创建一个链表数组来完成这段代码

例如:

list array [10]; /* or something like that... */

如果需要,我准备提供更多细节。

这是我的数据结构代码:

struct node;
typedef struct node *ptr;
typedef ptr list;
typedef ptr postion;
struct node {
ptr next;
float factor;
};
/* method for creating nodes */
int main()
{
/* initialize array of linked lists */
}

这是您的数据结构:

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 failedn");
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]);

最新更新