Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions src/hw6_sortList/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
cmake_minimum_required(VERSION 4.0)
project(hw6_sortList C)

set(CMAKE_C_STANDARD 17)

add_executable(sortList
interactiveMain.c
sortList.c
)

67 changes: 67 additions & 0 deletions src/hw6_sortList/interactiveMain.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
#include <stdio.h>
#include "sortList.h"

int main(int argc, char* argv[])
{
struct List* list = createEmptyList();
int command, inputElement;

if (argc > 1 && strcmp(argv[1], "--test") == 0) {
runTests();
return 0;
}

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) {
while (getchar() != '\n'); // очистка ввода
continue;
}

switch (command) {
case 0:
printf("Совершён выход\n");
deleteList(list);
return 0;

case 1:
printf("Введите значение для добавления: ");

if (scanf("%d", &inputElement) != 1) {
printf("Ошибка: вводите только цифры\n");
while (getchar() != '\n');
continue;
}
insertElement(list, inputElement);
break;

case 2:
printf("Введите значение для удаления:");

if (scanf("%d", &inputElement) != 1) {
printf("Ошибка: вводите только цифры\n");
while (getchar() != '\n');
continue;
}
if (deleteElement(list, inputElement)) {
printf("Значение было удалено\n");
} else {
printf("Элемент не найден\n");
}
break;

case 3:
printList(list);
break;

default:
printf("Введена неподдерживаемая команда: можно только 0,1,2,3\n");
}
}
}
110 changes: 110 additions & 0 deletions src/hw6_sortList/sortList.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
#include <stdio.h>
#include <stdlib.h>
#include "sortList.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;
}

// Удаление всего списка
void deleteList(struct List* list)
{
struct Node* curr = list->head;
while (curr) {
struct Node* tempNode = curr;
curr = curr->next;
free(tempNode);
}

free(list);
}

// Вставка элемента
void insertElement(struct List* list, int element)
{
struct Node* newNode = malloc(sizeof(struct Node));
if (!newNode) {
printf("Ошибка выделения памяти\n");
return;
}

newNode->data = element;
newNode->next = NULL;

if (!list->head || list->head->data >= element) {
newNode->next = list->head;
list->head = newNode;
list->size++;
return;
}

// Поиск места
struct Node* curr = list->head;
while (curr->next && curr->next->data < element) {
curr = curr->next;
}

newNode->next = curr->next;
curr->next = newNode;
list->size++;
}

// Удаление элемента
int deleteElement(struct List* list, int element)
{
if (!list->head) {
return 0;
}

if (list->head->data == element) {
struct Node* tempNode = list->head;
list->head = list->head->next;
free(tempNode);
list->size--;
return 1;
}

// Поиск элемента
struct Node* curr = list->head;
while (curr->next && curr->next->data != element) {
curr = curr->next;
}

if (!curr->next) {
return 0; // не найденн
}

struct Node* tempNode = curr->next;
curr->next = tempNode->next;
free(tempNode);
list->size--;
return 1;
}

// Печать списка
void printList(struct List* list)
{
if (!list->head) {
printf("Список пуст\n");
return;
}

struct Node* curr = list->head;
printf("[");
while (curr) {
printf("%d", curr->data);
if (curr->next) printf(", ");
curr = curr->next;
}
printf("]\n");
}

28 changes: 28 additions & 0 deletions src/hw6_sortList/sortList.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
#pragma once

struct Node {
int data;
struct Node* next;
};

struct List {
struct Node* head;
int size;
};

// Создание пустого списка
struct List* createEmptyList();

// Реализация команды 0 - выйти:
// Удаление всего списка для освобождения и выхода
void deleteList(struct List* list);

// Реализация команды 1 - добавить значениe в сортированный список:
void insertElement(struct List* list, int element);

// Реализация команды 2 – удалить значение из списка:
int deleteElement(struct List* list, int element);

// Реализация команды 3 – распечатать список:
void printList(struct List* list);

6 changes: 6 additions & 0 deletions src/hw6_sortList/sortList_tests/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
cmake_minimum_required(VERSION 4.0)
project(sortList_tests C)

set(CMAKE_C_STANDARD 17)

add_executable(sortList_tests testsForSortList.c)
137 changes: 137 additions & 0 deletions src/hw6_sortList/sortList_tests/testsForSortList.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
#include <stdio.h>
#include "testsForSortList.h"

// Создание списка из массива чтобы не было 20-ти insert
struct List* createListFromArr(int arr[], int n) {
struct List* list = createEmptyList();
for (int i = 0; i < n; i++) {
insertElement(list, arr[i]);
}
return list;
}

// Проверка того, что сортировка списка соответствует expected
int checkList(struct List* list, int arr[], int n) {
if (list->size != n) {
return 0;
}
struct Node* curr = list->head;
for (int i = 0; i < n; i++) {
if (!curr || curr->data != arr[i]) {
return 0;
}
curr = curr->next;
}
return 1;
}

// Тесты
int testInsertFirstElement() {
int expected[1] = {10};
struct List* lst = createEmptyList();
insertElement(lst, 10);

int res = checkList(lst, expected, 1);
deleteList(lst);
return res;
}

int testInsertMany() {
int initial[] = {1, 3, 7819};
int expected[6] = {-1, 0, 1, 3, 5, 7819};
struct List* lst = createListFromArr(initial, 3);

insertElement(lst, -1);
insertElement(lst, 0);
insertElement(lst, 5);

int res = checkList(lst, expected, 6);
deleteList(lst);
return res;
}

int testInsertDuplicates() {
int initial[] = {4, 2, 666};
int expected[6] = {-5, -5, 2, 2, 4, 666};
struct List* lst = createListFromArr(initial, 3);

insertElement(lst, -5);
insertElement(lst, -5);
insertElement(lst, 2);

int res = checkList(lst, expected, 6);
deleteList(lst);
return res;
}

int testDeleteLastElement() {
int initial[] = {52};
int expected[1] = {};
struct List* lst = createListFromArr(initial, 1);
deleteElement(lst, 52);

int res = checkList(lst, expected, 0);
deleteList(lst);
return res;
}

int testDeleteMultiple() {
int initial[] = {-100, 0, 3, 5, 7, 999};
int expected[3] = {0, 3, 5};
struct List* lst = createListFromArr(initial, 6);

deleteElement(lst, -100); // начало
deleteElement(lst, 7); // середина
deleteElement(lst, 999); // конец

int res = checkList(lst, expected, 3);
deleteList(lst);
return res;
}

int testDeleteDuplicates() {
int initial[] = {-1, 3, 0, 3, 5, 0, -1, 3, 3};
int expected[5] = {-1, -1, 3, 3, 5};
struct List* lst = createListFromArr(initial, 9);

deleteElement(lst, 3);
deleteElement(lst, 3);
deleteElement(lst, 0);
deleteElement(lst, 0);

int res = checkList(lst, expected, 5);
deleteList(lst);
return res;
}

int testDeleteNonexistent() {
int initial[] = {1, 2, 3};
int expected[1] = {};
struct List* lst = createListFromArr(initial, 3);

deleteElement(lst, 1);
deleteElement(lst, 2);
deleteElement(lst, 3);
deleteElement(lst, 10000);

int res = checkList(lst, expected, 0);
deleteList(lst);
return res;
}

// Вывод результатов и логика определения пройденности
void printTestResult(char* testName, int result) {
printf("%s: %s\n", testName, result ? "пройден!" : "НЕ пройден");
}

void runTests() {
printTestResult("Тест 1: Вставка первого элемента", testInsertFirstElement());
printTestResult("Тест 2: Вставка нескольких элементов", testInsertMany());
printTestResult("Тест 3: Вставка повторяющихся элементов", testInsertDuplicates());
printTestResult("Тест 4: Удаление единственного элемента", testDeleteLastElement());
printTestResult("Тест 5: Удаление элементов в начале, середине, конце", testDeleteMultiple());
printTestResult("Тест 6: Удаление дубликатов элементов", testDeleteDuplicates());
printTestResult("Тест 7: Удаление несуществующего элемента", testDeleteNonexistent());

printf("Конец тестов!\n");
}
Loading