해결법
- while문을 이용해서 swapped 상태를 유지.
- 조건: swapped == 1
- swapped를 0으로 만듬
문제
Assignment name : sort_list
Expected files : sort_list.c
Allowed functions:
--------------------------------------------------------------------------------
Write the following functions:
t_list *sort_list(t_list* lst, int (*cmp)(int, int));
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.
You must use the type t_list described in the file list.h
that is provided to you. You must include that file
(#include "list.h"), but you must not turn it in. We will use our own
to compile your assignment.
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, the following function used as cmp will sort the list
in ascending order:
int ascending(int a, int b)
{
return (a <= b);
}
코드
c
typedef struct s_list t_list;
struct s_list
{
int data;
t_list *next;
};
c
#include "list.h"
#include <stdlib.h>
void change_data(t_list *a, t_list *b)
{
int tmp;
tmp = a->data;
a->data = b->data;
b->data = tmp;
}
t_list *sort_list(t_list *lst, int (*cmp)(int, int))
{
t_list *cur = lst;
t_list *obj;
while (cur)
{
obj = cur->next;
while (obj)
{
if ((*cmp)(cur->data, obj->data) == 0)
change_data(cur, obj);
obj = obj->next;
}
cur = cur->next;
}
return (lst);
}
#include <stdio.h>
int ascending(int a, int b)
{
return (a <= b);
}
int main()
{
t_list *list = (t_list *)malloc(sizeof(t_list));
list->data = 2;
list->next = (t_list *)malloc(sizeof(t_list));
list->next->data = 1;
list->next->next = (t_list *)malloc(sizeof(t_list));
list->next->next->data = 7;
list->next->next->next = (t_list *)malloc(sizeof(t_list));
list->next->next->next->data = 10;
list->next->next->next->next = (t_list *)malloc(sizeof(t_list));
list->next->next->next->next->data = 9;
t_list *cur = list;
while (cur)
{
printf("%d ", cur->data);
cur = cur->next;
}
int (*cmp)(int, int) = ascending;
list = sort_list(list, cmp);
printf("\n");
cur = list;
while (cur)
{
printf("%d ", cur->data);
cur = cur->next;
}
}