I have a slight problem with sorting in linked lists. i have a doubly linked list that needs sorting after intital input, the swap function is what i intend to use, but the problem herein lies that it screws up any header pointers there may be. I cannot sort the list by jusr replacing data as there are too many variables and they can change in the course of development (new variables can be added or deleted)
task *taskHeader;
struct task{
task *pprev;
//large number of variables
int number;
task *pnext;
task(){
pprev = NULL;
pnext = NULL;
}
}
//swap function
void swap(task *task2, task *task3)
task* task1 = task2->prev; // alias for readability
task* task4 = task3->next; // alias for readability
if(task1!=NULL) task1->next = task3;
task3->prev = task1;
task3->next = task2;
task2->prev = task3;
task2->next = task4;
if(task4!=NULL) task4->prev = task2;
}
void sort(task *taskHeader){
task *temp = taskHeader;
while(temp != NULL){
if(temp->number < temp->pnext->number) swap(temp, temp->pnext);
}
}
how should i append the swap function to keep my headers intact and not crash when swapping start or end task nodes? currently i do this by adding NULL checks into the swap function to keep the function from going out of bounds and ending up with pointer faults, but is there a better way to solve this?
should i just traverse the linked list back til i reach a point where pprev == NULL and change the header to point towards that node?