Created
December 25, 2023 19:24
-
-
Save MzHmO/fefeedb98e0f4cf5a47ba440ad6cc327 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
// Определяем структуру для узла списка | |
typedef struct Node { | |
int value; | |
struct Node* next; | |
} Node; | |
// Вспомогательная функция для добавления узла к списку | |
void append(Node** head, int val) { | |
Node* new_node = (Node*)malloc(sizeof(Node)); | |
new_node->value = val; | |
new_node->next = NULL; | |
if (*head == NULL) { | |
*head = new_node; | |
} | |
else { | |
Node* last = *head; | |
while (last->next != NULL) { | |
last = last->next; | |
} | |
last->next = new_node; | |
} | |
} | |
// Функция сравнения для qsort | |
int compare(const void* a, const void* b) { | |
int int_a = *((const int*)a); | |
int int_b = *((const int*)b); | |
return (int_a > int_b) - (int_a < int_b); | |
} | |
// Функция для печати массива | |
void print_array(const int* arr, int n) { | |
for (int i = 0; i < n; i++) { | |
printf("%d ", arr[i]); | |
} | |
printf("\n"); | |
} | |
int main() { | |
int array[] = { 5, 10, 8, 3, 6, 12 }; | |
int length = sizeof(array) / sizeof(array[0]); | |
Node* even_list = NULL; // Голова списка для четных чисел | |
Node* current = NULL; // Текущий узел для обхода списка | |
// Создание списка из четных элементов | |
for (int i = 0; i < length; ++i) { | |
if (array[i] % 2 == 0) { | |
append(&even_list, array[i]); | |
} | |
} | |
// Подсчет количества четных элементов и создание массива для сортировки | |
int even_count = 0; | |
current = even_list; | |
while (current) { | |
even_count++; | |
current = current->next; | |
} | |
// Создание массива для хранения четных элементов | |
int* even_array = (int*)malloc(even_count * sizeof(int)); | |
// Копирование четных элементов в массив для сортировки | |
current = even_list; | |
for (int i = 0; current; ++i) { | |
even_array[i] = current->value; | |
current = current->next; | |
} | |
// Сортировка четных элементов | |
qsort(even_array, even_count, sizeof(int), compare); | |
// Вставка отсортированных четных элементов обратно в изначальный массив | |
current = even_list; | |
for (int i = 0, j = 0; i < length && j < even_count; ++i) { | |
if (array[i] % 2 == 0) { | |
array[i] = even_array[j++]; | |
} | |
} | |
// Освобождение памяти | |
free(even_array); | |
while (even_list) { | |
Node* next = even_list->next; | |
free(even_list); | |
even_list = next; | |
} | |
// Вывод отсортированного по определенным правилам массива | |
print_array(array, length); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment