I have a doubly linked list from which I need to occasionally delete elements (any elements that have a type value different from 0). The function I have seems to work, but looking at it, I think I could probably make the logic cleaner. If anyone has some suggestions for cutting down on redundant code to make this more readable, I would appreciate it.
The structs in questions are declared here, with irrelevent variabled omitted:
Code:
struct Event
{
//...
int type;
//...
struct Event *next;
struct Event *prev;
};
typedef struct Event event;
Code:
event *delete_bad_events(event *head)
{
event *newhead;
event *current;
event *tempnext;
event *tempprev;
event *temp;
current = head;
newhead = head;
while (current)
{
if (current->type != 0)
{
tempnext = current->next;
tempprev = current->prev;
temp = current;
current = current->next;
free_single_event(temp);
if (tempprev && tempnext)
{
tempprev->next = tempnext;
tempnext->prev = tempprev;
}
else if (!tempprev && tempnext) //head of the list
{
newhead = tempnext;
tempnext->prev = NULL;
}
else if (tempprev && !tempnext) //end of the list
{
tempprev->next = NULL;
}
else if (!tempprev && !tempnext) //singleton list, odd case
{
newhead = NULL;
}
}
else
{
current = current->next;
}
}
return newhead;
}