-
Notifications
You must be signed in to change notification settings - Fork 0
/
1000-sort_deck.c
79 lines (62 loc) · 1.44 KB
/
1000-sort_deck.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#include "deck.h"
#include "sort.h"
#include <stdlib.h>
#include <string.h>
/**
* compare_cards - Compare 2 cards based on their values and kinds.
* @card1: Pointer to the 1st card.
* @card2: Pointer to the 2nd card.
*
* Return: Negative value if card1 is less than card2,
* Positive value if card1 is greater than card2,
* Zero if card1 is equal to card2.
*/
int compare_cards(const void *card1, const void *card2)
{
const card_t *c1 = *(const card_t **)card1;
const card_t *c2 = *(const card_t **)card2;
int value_comparison = strcmp(c1->value, c2->value);
if (value_comparison != 0)
return (value_comparison);
if (c1->kind < c2->kind)
return (-1);
else if (c1->kind > c2->kind)
return (1);
else
return (0);
}
/**
* sort_deck - Sorts a deck of cards in ascending order.
* @deck: Pointer to the head of the deck.
*/
void sort_deck(deck_node_t **deck)
{
deck_node_t *current, *temp;
card_t *cards[52];
int i;
if (deck == NULL || *deck == NULL)
return;
current = *deck;
i = 0;
while (current != NULL)
{
cards[i++] = (card_t *)current->card;
temp = current;
current = current->next;
free(temp);
}
qsort(cards, 52, sizeof(card_t *), compare_cards);
*deck = NULL;
for (i = 0; i < 52; i++)
{
current = malloc(sizeof(deck_node_t));
if (current == NULL)
return;
current->card = cards[i];
current->prev = NULL;
current->next = *deck;
if (*deck != NULL)
(*deck)->prev = current;
*deck = current;
}
}