如何使用以下结构初始化双向链表?

问题描述 投票:0回答:1

这是我的代码,我知道我没有写太多,但是我不知道如何使用给定的结构初始化双向链表。

给定的结构(我无法对其进行任何更改)

/* a node in the linked list */
typedef struct Node
{
    void *data;
    struct Node *next;
    struct Node *prev;
} Node;

/* a linked list */
typedef struct LinkedList
{
    Node *head;
    Node *tail;
} LinkedList;

这是我的代码

/* create a new linked list */
/* returns a pointer to the newly created list */
/* print an error message and return NULL if an error occurs */
LinkedList *initialise_linked_list(void)
{
    LinkedList *list;
    list = (LinkedList *)malloc(sizeof(LinkedList));
        if (list == 0)
        {
            fprintf(stderr, "Warning: Memory could not be allocated for the new created list.");
            printf("\n");
            return 0;
        }
    return list;
}
c struct linked-list doubly-linked-list
1个回答
1
投票

您可以通过以下方式完成

LinkedList initialise_linked_list(void)
{
    LinkedList list = { NULL, NULL };
    return list;
}

并调用类似的函数>

LinkedList list = initialise_linked_list();

另一种方法如下

void initialise_linked_list( LinkedList *list )
{
    list->head = NULL;
    list->tail = NULL;  
}

和这样称呼

LinkedList list;
initialise_linked_list( &list );

无需动态分配列表本身。将动态分配列表中的节点。

关于您的功能,它不会初始化链表。它只是为结构分配内存。至少应使用malloc代替calloc

例如

LinkedList * initialise_linked_list( void )
{
    LinkedList *list = calloc( 1, sizeof( LinkedList ) );

    if ( list == NULL )
    {
        fprintf(stderr, "Warning: Memory could not be allocated for the new created list.\n");
    }

    return list;
}
© www.soinside.com 2019 - 2024. All rights reserved.