-
Notifications
You must be signed in to change notification settings - Fork 0
Hw10: Тесты к Сортированному списку #7
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
DolzhenkoAlexa
wants to merge
3
commits into
main
Choose a base branch
from
HW10_Dolzhenko_tests
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,9 @@ | ||
| Тесты к Сортированному списку | ||
|
|
||
| Запуск тестов: | ||
| gcc tests.c sortListForTests.c -o program | ||
| .\program.exe --test | ||
|
|
||
| Можно запустить интерактивный режим: | ||
| .\program.exe | ||
| (без флага) |
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Нужно использовать сортированный список из домашки про него, а не писать заново. |
This file contains hidden or 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,254 @@ | ||
| // | ||
| // Created by sasha on 19.11.2025. | ||
| // | ||
| #include "sortListForTests.h" | ||
| #include <stdio.h> | ||
| #include <stdlib.h> | ||
| #include <string.h> | ||
|
|
||
| // Создание пустого списка | ||
| struct List* createEmptyList() | ||
| { | ||
| struct List* list = malloc(sizeof(struct List)); | ||
| if (!list) { | ||
| fprintf(stderr, "Ошибка выделения памяти\n"); | ||
| exit(1); | ||
| } | ||
| list->head = NULL; | ||
| list->size = 0; | ||
| return list; | ||
| } | ||
|
|
||
| // Получение элемента по индексу | ||
| int getElement(struct List* list, int i) | ||
| { | ||
| // Проверка корректности индекса | ||
| if (i < 0 || i >= list->size) { | ||
| printf("Некорректный индекс: он не может быть < 0 или больше размера списка\n"); | ||
| return -1; | ||
| } | ||
|
|
||
| struct Node* currNode = list->head; | ||
| while (i--) { | ||
| currNode = currNode->next; | ||
| } | ||
| return currNode->data; | ||
| } | ||
|
|
||
| // Реализация команды 0 - выйти: | ||
| // Удаление всего списка для освобождения и выхода | ||
| void deleteList(struct List* list) | ||
| { | ||
| struct Node* currNode = list->head; | ||
| // Удаление узлов | ||
| while (currNode) { | ||
| struct Node* tempNode = currNode; | ||
| currNode = currNode->next; | ||
| free(tempNode); | ||
| } | ||
| // Освобождение памяти | ||
| free(list); | ||
| } | ||
|
|
||
| // Реализация команды 1 - добавить значение в сортированный список: | ||
| // Поиск позиции для вставки элемента в список | ||
| int findPosition(struct List* list, int element) | ||
| { | ||
| if (list->size == 0) | ||
| return 0; | ||
|
|
||
| struct Node* currNode = list->head; | ||
| int position = 0; | ||
|
|
||
| // Ищем первую позицию, где след элемент больше нового значения | ||
| // Так как список отсортирован, то прошлый будет или больше или равен вставляемому | ||
| while (currNode && currNode->data < element) { | ||
| currNode = currNode->next; | ||
| position++; | ||
| } | ||
| return position; | ||
| } | ||
|
|
||
| // Вставка элемента в список по заданному индексу | ||
| void insertElement(struct List* list, int i, int element) | ||
| { | ||
| // Проверка корректности индекса | ||
| if (i < 0 || i > list->size) { | ||
| printf("Некорректный индекс: он не может быть < 0 или больше размера списка\n"); | ||
| return; | ||
| } | ||
|
|
||
| // Создание нового узла | ||
| struct Node* newNode = malloc(sizeof(struct Node)); | ||
| if (!newNode) { | ||
| printf("Ошибка выделения памяти для саздания нового узла\n"); | ||
| return; | ||
| } | ||
| newNode->data = element; | ||
| // Вставка | ||
| if (i == 0) { | ||
| newNode->next = list->head; | ||
| list->head = newNode; | ||
| } else { | ||
| // Поиск позиции для вставки | ||
| struct Node* currNode = list->head; | ||
| int pos = 1; | ||
| while (pos < i) { | ||
| currNode = currNode->next; | ||
| pos++; | ||
| } | ||
| newNode->next = currNode->next; | ||
| currNode->next = newNode; | ||
| } | ||
| list->size++; | ||
| } | ||
|
|
||
| // Реализация команды 2 – удалить значение из списка: | ||
| // Проверка наличия значения в списке | ||
| int checkElement(struct List* list, int element) | ||
| { | ||
| struct Node* currNode = list->head; | ||
| int position = 0; | ||
|
|
||
| while (currNode) { | ||
| if (currNode->data == element) { | ||
| return position; | ||
| } | ||
| currNode = currNode->next; | ||
| position++; | ||
| } | ||
| return -1; | ||
| } | ||
|
|
||
| // Удаление элемента по индексу | ||
| void deleteElement(struct List* list, int i) | ||
| { | ||
| // проверка корректности индекса | ||
| if (i < 0 || i >= list->size) { | ||
| printf("Некорректный индекс: он не может быть < 0 или больше размера списка\n"); | ||
| return; | ||
| } | ||
| struct Node* nodeForDeletion; | ||
| // Удаление из начала списка | ||
| if (i == 0) { | ||
| nodeForDeletion = list->head; | ||
| list->head = list->head->next; | ||
| } else { | ||
| // Поиск узла перед удаляемым | ||
| struct Node* currNode = list->head; | ||
| int pos = 1; | ||
| while (pos < i) { | ||
| currNode = currNode->next; | ||
| pos++; | ||
| } | ||
| nodeForDeletion = currNode->next; | ||
| currNode->next = nodeForDeletion->next; | ||
| } | ||
| // Освобождение памяти | ||
| free(nodeForDeletion); | ||
| list->size--; | ||
| } | ||
|
|
||
| // Реализация команды 3 – распечатать список: | ||
| // Печать содержимого списка | ||
| void printList(struct List* list) | ||
| { | ||
| if (list->size == 0) { | ||
| printf("Список пустой\n"); | ||
| return; | ||
| } | ||
|
|
||
| struct Node* currNode = list->head; | ||
| printf("Содержание списка:\n"); | ||
| printf("["); | ||
| while (currNode) { | ||
| printf("%d", currNode->data); | ||
| if (currNode->next) printf(", "); | ||
| currNode = currNode->next; | ||
| } | ||
| printf("]\n"); | ||
| } | ||
|
|
||
|
|
||
| // Функция main для реализации выбора команд 0-3 пользователем | ||
| int main(int argc, char* argv[]) | ||
| { | ||
| // Дополнительный код для того, чтобы работал флаг | ||
| if (argc > 1 && strcmp(argv[1], "--test") == 0) { | ||
| runTests(); | ||
| return 0; | ||
| } | ||
|
|
||
| struct List* list = createEmptyList(); | ||
| int command, inputElement; | ||
|
|
||
| while (1) { | ||
| printf("Команды:\n"); | ||
| printf("0 - Выйти\n"); | ||
| printf("1 - Добавить значение в сортированный список\n"); | ||
| printf("2 - Удалить значение из списка\n"); | ||
| printf("3 - Распечатать список\n"); | ||
| printf("Выберите команду (0,1,2,3): "); | ||
|
|
||
|
|
||
| if (scanf("%d", &command) != 1) { | ||
| printf("Ошибка: вводите только цифры\n"); | ||
| int ch; | ||
| while ((ch = getchar()) != '\n'); | ||
|
|
||
| continue; | ||
| } | ||
|
|
||
| switch (command) { | ||
| case 0: | ||
| printf("Совершён выход\n"); | ||
| deleteList(list); | ||
| return 0; | ||
|
|
||
| case 1: | ||
| printf("Введите значение для добавления: "); | ||
|
|
||
| if (scanf("%d", &inputElement) != 1) { | ||
| printf("Ошибка: вводите только цифры\n"); | ||
|
|
||
| int ch; | ||
| while ((ch = getchar()) != '\n'); | ||
|
|
||
| continue; | ||
| } | ||
|
|
||
| int position1 = findPosition(list, inputElement); | ||
| insertElement(list, position1, inputElement); | ||
| printf("Значение было добавлено на позицию %d\n", position1); | ||
| break; | ||
|
|
||
| case 2: | ||
| printf("Введите значение для удаления:"); | ||
|
|
||
| if (scanf("%d", &inputElement) != 1) { | ||
| printf("Ошибка: вводите только цифры\n"); | ||
|
|
||
| int ch; | ||
| while ((ch = getchar()) != '\n'); | ||
|
|
||
| continue; | ||
| } | ||
|
|
||
| int position2 = checkElement(list, inputElement); | ||
| if (position2 != -1) { | ||
| deleteElement(list, position2); | ||
| printf("Значение было удалено с позиции %d\n", position2); | ||
| } else { | ||
| printf("Значение не найдено\n"); | ||
| } | ||
| break; | ||
|
|
||
| case 3: | ||
| printList(list); | ||
| break; | ||
|
|
||
| default: | ||
| printf("Введена неподдерживаемая команда: можно только 0,1,2,3\n"); | ||
| } | ||
| } | ||
| } |
This file contains hidden or 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,52 @@ | ||
| // | ||
| // Created by sasha on 19.11.2025. | ||
| // | ||
|
|
||
| #ifndef SORTLISTFORTESTS_MAIN_H | ||
| #define SORTLISTFORTESTS_MAIN_H | ||
|
|
||
| // Cтруктура для узла списка | ||
| struct Node { | ||
| int data; // данные узла | ||
| struct Node* next; // указатель на следующий узел | ||
| }; | ||
|
|
||
|
|
||
| // Структура для самого списка | ||
| struct List { | ||
| struct Node* head; // указатель на начало списка | ||
| int size; // размер списка | ||
| }; | ||
|
|
||
| // Создание пустого списка | ||
| struct List* createEmptyList(); | ||
|
|
||
| // Получение элемента по индексу | ||
| int getElement(struct List* list, int i); | ||
|
|
||
| // Реализация команды 0 - выйти: | ||
| // Удаление всего списка для освобождения и выхода | ||
| void deleteList(struct List* list); | ||
|
|
||
| // Реализация команды 1 - добавить значениe в сортированный список: | ||
| // Поиск позиции для вставки элемента в список | ||
| int findPosition(struct List* list, int element); | ||
|
|
||
| // Вставка элемента в список по заданному индексу | ||
| void insertElement(struct List* list, int i, int element); | ||
|
|
||
| // Реализация команды 2 – удалить значение из списка: | ||
| // Проверка наличия значения в списке | ||
| int checkElement(struct List* list, int element); | ||
|
|
||
| // Удаление элемента по индексу | ||
| void deleteElement(struct List* list, int i); | ||
|
|
||
| // Реализация команды 3 – распечатать список: | ||
| // распечатывание содержимое списка | ||
| void printList(struct List* list); | ||
|
|
||
| void runTests(); | ||
|
|
||
|
|
||
| #endif //SORTLISTFORTESTS_MAIN_H |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Если я правильно понимаю, все домашки, начиная с этой, должны использовать CMake.