Home > database >  How to create a function in C to initialize a linked list with a dummy node
How to create a function in C to initialize a linked list with a dummy node

Time:07-15

I'm trying to write a function generate_list which will generate a list with one node initialized to with val as 0 and next as NULL. generate_list should not take any arguments.

Here are the requirements:

define a struct datatype named node which contains an integer number and a pointer to the next node of the list.

define a new datatype named list, defined as a pointer to the node. list represents the list's head.

define a function of type list called generate_list which takes no parameters and returns a list with a dummy node (integer number = 0, pointer = NULL).

I tried something like this:

typedef struct list_node {
   int val;
   struct list_node *next;
}

typedef struct a_list {
   node *head;
}

list generate_list() {
    list *l = malloc(sizeof(*l));
    node d_node;
    l->head = &d_node;
    d_node.val = 0;
    d_node.next = NULL;
    return *l;
}

I am not sure if I did correctly the second part and how could I implement the function?

what should I return from it?

CodePudding user response:

you actually did pretty well. But, you must return a pointer to the list from your generate_list function.

It should be like this:

a_list *generate_list()
{
    a_list *list = (a_list *)malloc(sizeof(a_list));
    list_node *head_node = (list_node *)malloc(sizeof(list_node);
    
    list->head = head_node;
    
    head_node->val = 0;
    head_node->next = NULL;
    
    return list;
}

now you want to generate your list inside the function. but, you also want to return an accessible list. Hence, you must malloc it all (the list and the node) so it wouldn't be a local variable (allocated on the stack and disappear after the function returns).

CodePudding user response:

There are some problems in your code:

  • you should include <stdlib.h>

  • the type definitions must include the type name and end with a ;

  • the argument list of generate_list should be defined as (void), not () which has a different meaning in C (unlike C ).

  • the first node should be allocated, not an automatic variable that will become invalid as soon as the function returns.

  • the list itself should not be allocated, but returned by value, a peculiar requirement that is explicit in the problem specification.

Here is a modified version:

#include <stdlib.h>

typedef struct node {
    int val;
    struct node *next;
} node;

typedef struct list {
    node *head;
} list;

list generate_list(void) {
    list l;
    l.head = malloc(sizeof(*n));
    if (l.head == NULL) {
        /* abort with an error message */
        perror("generate_list");
        exit(1);
    }
    l.head->val = 0;
    l.head->next = NULL;
    return l;
}
  • Related