【问题标题】:Create an array of linked lists in C based on a given struct基于给定结构在 C 中创建一个链表数组
【发布时间】:2021-06-30 01:22:14
【问题描述】:

我需要通过在 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 */
}

【问题讨论】:

  • 为什么要指定这个typedef:typedef ptr postion;
  • 您确定要创建数组包含链表还是只想创建一个 i> 链表?

标签: arrays c linked-list


【解决方案1】:

这是你的数据结构:

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

【讨论】:

    猜你喜欢
    • 2011-11-06
    • 2012-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多