Hey I am writing a double linked list dictionary of sorts. All of my functions were properly (add element after, move pointer, search, etc.). However, something is wrong with my add before function. Initially it adds elements fine, however if I decide to move the pointer to a new element and then attempt to add an element before the pointer element.. that element becomes the pointer and everything before that deletes. Here is an example of my output.
i 1 1
Student List [1] = {1}
i 1 2 /* i is add before */
Student List [1] = {2} 1
a 1 3 /*a is add after*/
Student List [1] = 2 {3} 1
n 1 /*change pointer to next element*/
Student List [1] = 2 3 {1}
i 1 4
Student List [1] = {4} 1
^^^^ This is where it deletes any suggestions?

Here is my code for add before:

LList_t *llist_insert_before(LList_t *ele, int val)

{
    LList_t *newNode = llist_create(val);
    LList_t *curr, *nexty, *prevy;
    curr = ele;

    if(curr == NULL){
        return newNode;
    }

    else if(curr->prev != NULL){
        curr->prev = newNode;
        newNode->next = curr;
        return newNode;
    }
    else if (curr->prev == NULL){
        prevy = curr->prev;
        newNode->prev = prevy;
        curr->prev = newNode;
        newNode->next = curr;
        return newNode;
    }
}

Recommended Answers

All 2 Replies

can you post full code with main..

Also inside the elif on line 12 you should update the curr->prev->next before updating curr->prev .
Inn other words, with line 12 to 16 you're inserting newNode between curr and curr->prev , so you need to update links of curr->prev and curr .

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.