0

I am working on a generic form of a double linked list, so I have :
list structure :

int size;  
struct elem *head;  
struct elem *current;  
struct elem *tail;

elem structure :

void *data;  
struct elem *next;  
struct elem *prev;

I am having a hard time implementing a function allowing me to push a new element before the current one. Here is what I came up with for the moment :

t_list *my_list_add_before(t_list *list, void *data)  
{
    struct elem *elem = malloc(sizeof(*elem));
    elem->data = data;
    if(list->size == 0)
    {
        list->head = elem;
        list->current = elem;
        list->tail = elem;
        elem->prev = NULL;
        elem->next = NULL;
    }
    else
    {
       elem->next = list->current;
       elem->prev = list->current->prev;
       elem->prev->next = elem;
       list->current->prev = elem;
    }
    list->size = list->size + 1;
    return (list);
}

But my list->head->next seem to point to NULL. What is the issue?

0

1 Answer 1

2

You should modify list->current->prev->next before list->current->prev, currently you effectively do elem->next = elem.

Sign up to request clarification or add additional context in comments.

2 Comments

I swapped both line as you suggested, but when I try to display my linked list, I can only display one line. (my list-size = 45)
You are also not treatingk the case where list->current == list->head correctly. You need to update list->head after inserting before the current head.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.