Why are you allocating curr and prev in this at all? Aren't they just for iterating the list? Please explain why you think that is necessary, as that code will leak memory because of it, and you need to sort out your misunderstanding.
The idea is pretty simple here:
- You have your new node, allocated and assigned appropriate values.
- You have the list into which the new node is to be inserted.
- If the list is empty, just insert as the head.
So far so good. Now, if the list is not empty:
- set curr to the head and prev to NULL.
- iterate (pseudocode):
Code:
while (curr) {
if (curr title is greater than new node title) { // your comparison call
// we insert in front of curr
if (prev) {
set prev->next to new node
}
set newnode->next to curr
done! (so break from loop)
}
prev = curr;
curr = curr->next;
}
if (!curr) { // the node was not inserted, so it should go on the end
prev->next = new node
}
Make sense?