List points to the first element in the list.
All the nodes is intended to be allocated with malloc.
The task is to insert the integer toinsert into the list before the node containing before. And return the list resulting from the insertion.
Code:
typedef struct dlintlist_struct dlintlist_t;
struct dlintlist_struct {
int item;
dlintlist_t *next;
dlintlist_t *prev;
};
dlintlist_t *insert(dlintlist_t *list, int before, int toinsert) {
dlintlist_t *new_node;
while (list != NULL && list->item != before) {
list = list->next;
}
if (list != NULL) {
new_node = malloc(sizeof(dlintlist_t));
new_node->prev = list->prev;
new_node->next = list;
list->prev->next = new_node;
}
return list;
}
There are 3,4 bugs in this code which I have to identify.
1. As you've traversed through list you lose track of the first pointer.
2. The number toinsert hasn't actually been inserted.
3. The declaration of typedef is incorrect as the structure dlintlist_struct hasn't yet been declared at that point.
I was expecting an error somewhere between the if statement, but I drew out the pointer diagram and I found it to be correct.