sort_list — Sort a Linked List
Allowed functions: none
This function must sort the list given as a parameter, using the function pointer cmp to select the order to apply, and returns a pointer to the first element of the sorted list. Duplications must remain. Inputs will always be consistent.
t_list *sort_list(t_list* lst, int (*cmp)(int, int));
Functions passed as cmp will always return a value different from 0 if a and b are in the right order, 0 otherwise. For example:
int ascending(int a, int b)
{
return (a <= b);
}
Solution
Download sort_list.c#include "list.h"
t_list *sort_list(t_list *lst, int (*cmp)(int, int)) {
t_list *cur;
int temp;
cur = lst;
while (cur->next) {
if (!cmp(cur->data, cur->next->data)) {
temp = cur->data;
cur->data = cur->next->data;
cur->next->data = temp;
cur = lst;
} else
cur = cur->next;
}
return (lst);
}
How It Works
Goal: Sort a linked list using a comparison function to determine the order.
Approach: Bubble sort adapted for linked lists — swap node data (not the nodes themselves) and restart on each swap.
Step by step:
- Start
curat the head of the list. - Compare
cur->dataandcur->next->datausing thecmpfunction pointer. - If
cmpreturns 0 (wrong order), swap the two nodes'datavalues and resetcurto the head to restart. - Otherwise, advance
curto the next node. The loop ends whencur->nextis NULL (full pass with no swaps).
Key concept: Sorting a linked list by swapping data instead of relinking nodes, and using a function pointer as a flexible comparator.