Skip to main content

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:

  1. Start cur at the head of the list.
  2. Compare cur->data and cur->next->data using the cmp function pointer.
  3. If cmp returns 0 (wrong order), swap the two nodes' data values and reset cur to the head to restart.
  4. Otherwise, advance cur to the next node. The loop ends when cur->next is 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.