Code:
USER *user = usertable[slot]; // Find our user based on slot #
(user->num_ratings)++; // Increase the number of ratings
RATING_NODE *prev = NULL; // We are going to keep track of the previous item, so we can do the insert
RATING_NODE *curr = user->ratings; // Start at the head of the user's 'ratings' list
// We are going to walk the list until either
// * The current nodes's item_id is greater than the rating we are adding
// * We reach the end of the list
while (curr != NULL) // While we have not reached the end of the list
{
if (rnode->item_id < curr->item_id) // If we have reahed the point where we want to insert
break; // then drop out of the loop
prev = curr; // Move onto the next item in the list
curr = curr->next;
}
// We now have three different places to insert
// - At the start of the list
// - In the middle of the list
// - At the end of the list
// It seems somebody has forgotten the 4th case - if the list is completely empty...
if (prev == NULL) { // Was prev never assigned anything but the initial NULL?
rnode->next = user->ratings; // We are inserting at the head of the list
user->ratings->prev = rnode; // THIS LINE SEEM WRONG.. a NULL pointer access if user->ratings is NULL???
user->ratings = rnode;
} else if (curr == NULL) { // Did we walk off the end of the list?
prev->next = rnode; // Insert at the end of the list - need to update 2 pointers
rnode->prev = prev;
} else { // Both prev and curr are not NULL, so we are in the middle of the list
prev->next = rnode; // Insert into the middle of the list - need to update 4 pointers
rnode->prev = prev;
rnode->next = curr;
curr->prev = rnode;
}