Tomiisme
Tomiisme

Reputation: 41

How to initialize a doubly linked list with the following structs?

This is my code, I know I did not write much, but I am not knowing how to initialize a doubly linked list with the given structs.

The given structs (I can`t change anything in them)

/* 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;

And this is my code

/* 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;
}

Upvotes: 0

Views: 737

Answers (1)

Vlad from Moscow
Vlad from Moscow

Reputation: 310930

You can do it the following way

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

and call the function like

LinkedList list = initialise_linked_list();

Another approach is the following

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

and call it like

LinkedList list;
initialise_linked_list( &list );

There is no need to allocate the list itself dynamically. It is nodes of the list that will be allocated dynamically.

As for your function then it does not initialize a linked list. It just allocates memory for the structure. At least instead of malloc you should use calloc.

For example

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;
}

Upvotes: 2

Related Questions