I’m working on a university assignment. I am trying to write a linked-list sort in C. I am not allowed to swap values – only pointers.
Here is my sorting function:
struct node *sort_list(struct node *head) {
bool swapped ;
struct node *cur = head, *first ;
if ( head == NULL || head->next == NULL ) return head ;
else {
do {
swapped = false ;
while ( cur != NULL && cur->next != NULL ){
if (cur->value > cur->next->value){
cur = swap_with_next( cur ) ;
swapped = true ;
}
cur = cur->next ;
}
} while (swapped == true) ;
}
return head ;
}
And the swap function:
struct node *swap_with_next(struct node *n) {
struct node *tmp ;
tmp = n ;
n = n->next ;
tmp->next = n->next ;
n->next = tmp ;
return n ;
}
Problem: Incorrect output:
input: 5->2->NULL
output: 5->NULL
input: 9->1->5->2->8->3
output: 9->5->8
Any help would be greatly appreciated!
Ok, so, let’s say there are 3 nodes A, B and C (in that order). You are trying to swap B and C. So, you are passing the pointer to B to the
swapfunction. Now, all the pointer manipulations are correct but, you miss one thing. A’s next pointer should point to C when you finish the swap. You never set this. When you finish the swap function, A’s next pointer still points to B which is obviously not correct. That’s the problem.