0

I am working in a project and I need to turn my doubly linked list, which works only with integer values, into an agnostic list. It means that it has to work with different data types, doesn'r matter if it is int, char, double, etc.

Here is part of what I did, being "val" the variable to receive an integer and manipulate it in the list:

typedef struct double_node{
    int val;
    struct double_node* prev;
    struct double_node* next;
} Node;

typedef struct double_linked_list{
    Node* begin;
    Node* end;
    size_t size;
} List;

Node* Node_create(int val){
    Node* node = (Node*) calloc(1, sizeof(Node));
    node->prev = NULL;
    node->next = NULL;
    node->val = val;

    return node;
}

Up there is how i created the nodes.

void List_add_first(List* L, int val){
    Node* p = Node_create(val);
    p->next = L->begin;

    if (empty_List(L))
    {
        L->end = p;
    }
    else{
        L->begin->prev = p;
    }
    L->begin = p;
    L->size++;
}

And up there is how I am adding elements (for now only integers) in the list.

Feel free to ask for more if it is necessary and thank you all for the help.

  • You can store a void pointer in a node as the node's payload when a node is created. Then you can write a traversal function that passes the payload to a callback function that is either stored in the list or passed to the traversal function. The `qsort` function, calling a comparison function is one example of such a thing. You can do something similar to the function that adds and deletes nodes. – Jeff Holt Apr 17 '22 at 04:31
  • Thank you for your response! Would you mind giving me an example of how i would do that? It might be something very simple. Since I am new in C some things are really abstract for me. – William Schmidt Apr 17 '22 at 04:35

0 Answers0