Вопрос пользователя:
В c++ для windows создайте вручную простой односвязный список. Реализуйте вручную
эффективную функцию сортировки этого списка – сортировку вставками
(insertions_sort).
Ответ нейросети:
Вот пример реализации односвязного списка и функции сортировки вставками на C++ для Windows:
```cpp
#include <iostream>
struct Node {
int data;
Node* next;
};
Node* insert(Node* head, int data) {
Node* newNode = new Node;
newNode->data = data;
newNode->next = nullptr;
if (head == nullptr) {
head = newNode;
} else {
Node* current = head;
while (current->next != nullptr) {
current = current->next;
}
current->next = newNode;
}
return head;
}
void printList(Node* head) {
Node* current = head;
while (current != nullptr) {
std::cout << current->data << " ";
current = current->next;
}
std::cout << std::endl;
}
Node* insertionSort(Node* head) {
if (head == nullptr || head->next == nullptr) {
return head;
}
Node* sorted = nullptr;
Node* current = head;
while (current != nullptr) {
Node* next = current->next;
if (sorted == nullptr || current->data < sorted->data) {
current->next = sorted;
sorted = current;
} else {
Node* search = sorted;
while (search->next != nullptr && search->next->data < current->data) {
search = search->next;
}
current->next = search->next;
search->next = current;
}
current = next;
}
return sorted;
}
int main() {
Node* head = nullptr;
head = insert(head, 3);
head = insert(head, 1);
head = insert(head, 4);
head = insert(head, 2);
head = insert(head, 5);
std::cout << "Original list: ";
printList(head);
head = insertionSort(head);
std::cout << "Sorted list: ";
printList(head);
return 0;
}
```
Этот код создает односвязный список с элементами 3, 1, 4, 2, 5, затем сортирует его с помощью сортировки вставками и выводит отсортированный список.