I am currently working on sorting a linked list in C as a homework assignment. I’m not looking for a code snippet as an answer, as I understand the value of figuring it out myself. I am receiving a segfault using the function below and I would really appreciate if someone could at least tell me why. The best I could figure out is that it is failing when reaching the following line:
if ( head->value > head->next->value ) {
EDIT: Changed this line to if (head->next != NULL && head->value > head->next->value){ and am no longer receiving segfaults. However, my output head pointer is giving me the last node in the linked-list. HALP.
I’m not totally sure where to go from here, and even the slightest nudge in the right direction would be very appreciated.
struct node *sort_list(struct node *head) {
bool swapped ;
struct node * tmp , * orig ;
orig = head ;
if ( head == NULL || head->next == NULL ) return head ;
else {
do {
swapped = false ;
if ( head->next != NULL && head->value > head->next->value ) {
tmp = head ;
head = head->next ;
tmp->next = head->next ;
head->next = tmp ;
swapped = true ;
}
head = head->next ;
} while ( swapped == true && head != NULL ) ;
}
return orig ;
}
Once head becomes the last element in the linked list, you get your segfault.
I don’t want to write the code since it’s homework, but add a conditional to check if head->next is null. If it is, you’ll want to set head back to the head of the list.
Your bubble sort will need multiple passes through the linked list to sort it. If you initialize your linked list with values 5,4,3,2,1 and print head and print temp and head. You’ll probably see 5,4 5,3 5,2 5,1 segfault
Also your sorting formula seems to be a bit off. If you have data such as 2,3,1. You’re code would see 2 and 3, swapped would become true and the function would return true.
You may want to use a loop inside to loop so that every iteration of the outer loop will cause 1 pass through the linked list. If there are no swaps after a pass through the entire linked list, then the data is sorted.
Hope this helps.
Edit
After
Add
You need to maintain your head pointer.
In the case of 5,4,3,6. It’ll sort it as follows
4,5,3,6
4,3,5,6
3,4,5,6
But your orig pointer was never updated, so your output will be truncated to 4,5,6.