0

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

Edited by dem10: n/a

2
Contributors
2
Replies
4
Views
6 Years
Discussion Span
Last Post by thekashyap
0

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 .

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.