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
159 changes: 159 additions & 0 deletions src/hw_6-1_sortList/hw_6-1_sortList.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
#include "hw_6-1_sortList.h"
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

после include<>

#include <stdio.h>
#include <stdlib.h>

// создание нового пустого списка
List* listCreate()
{
List* list = (List*)malloc(sizeof(List));
if (list == NULL) {
printf("Ошибка выделения памяти для списка\n");
exit(1);
}
list->head = NULL;
list->size = 0;
return list;
}

// вставка элемента в список по заданному индексу
void listInsert(List* list, int index, int value)
{
// проверка корректности индекса
if (index < 0 || index > list->size) {
printf("Некорректный индекс для вставки\n");
return;
}

// создаем новый узел
Node* newNode = (Node*)malloc(sizeof(Node));
if (newNode == NULL) {
printf("Ошибка выделения памяти для узла\n");
return;
}
newNode->data = value;

// вставка в начало списка
if (index == 0) {
newNode->next = list->head;
list->head = newNode;
} else {
// поиск позиции для вставки
Node* current = list->head;
for (int i = 0; i < index - 1; i++) {
current = current->next;
}
// вставка между узлами
newNode->next = current->next;
current->next = newNode;
}
list->size++;
}

// получение элемента по заданному индексу
int listGet(List* list, int index)
{
// проверка корректности индекса
if (index < 0 || index >= list->size) {
printf("Некорректный индекс для получения элемента\n");
return -1;
}

// поиск нужного узла
Node* current = list->head;
for (int i = 0; i < index; i++) {
current = current->next;
}
return current->data;
}

// удаление элемента по заданному индексу
void listRemove(List* list, int index)
{
// проверка корректности индекса
if (index < 0 || index >= list->size) {
printf("Некорректный индекс для удаления\n");
return;
}

Node* toDelete;
// удаление из начала списка
if (index == 0) {
toDelete = list->head;
list->head = list->head->next;
} else {
// поиск узла перед удаляемым
Node* current = list->head;
for (int i = 0; i < index - 1; i++) {
current = current->next;
}
toDelete = current->next;
current->next = toDelete->next;
}
// освобождение памяти
free(toDelete);
list->size--;
}

// распечатывание содержимое списка
void listPrint(List* list)
{
if (list->size == 0) {
printf("Список пуст\n");
return;
}

Node* current = list->head;
printf("Содержимое списка: ");
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}

// удаление всего списка (освобождает память)
void listDelete(List* list)
{
Node* current = list->head;
// последовательное удаление всех узлов
while (current != NULL) {
Node* temp = current;
current = current->next;
free(temp);
}
// освобождение структуры списка
free(list);
}

// находит позицию для вставки в сортированный список
int listPosition(List* list, int value)
{
if (list->size == 0)
return 0;

Node* current = list->head;
int position = 0;

// ищем первую позицию, где следующий элемент больше вставляемого значения
while (current != NULL && current->data < value) {
current = current->next;
position++;
}
return position;
}

// проверяет наличие значения в списке
int listContain(List* list, int value)
{
Node* current = list->head;
int position = 0;

while (current != NULL) {
if (current->data == value) {
return position;
}
current = current->next;
position++;
}
return -1;
}
44 changes: 44 additions & 0 deletions src/hw_6-1_sortList/hw_6-1_sortList.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
#ifndef SORTLIST_H
#define SORTLIST_H

// структура узла списка
typedef struct Node {
int data; // данные узла
struct Node* next; // указатель на следующий узел
} Node;

// структура списка
typedef struct {
Node* head; // указатель на начало списка
int size; // размер списка
} List;

// создание нового пустого списка
List* listCreate();

// вставка элемента в список по заданному индексу
void listInsert(List* list, int index, int value);

// получение элемента по заданному индексу
int listGet(List* list, int index);

// удаление элемента по заданному индексу
void listRemove(List* list, int index);

// распечатывание содержимое списка
void listPrint(List* list);

// удаление всего списка (освобождает память)
void listDelete(List* list);

// находит позицию для вставки в сортированный список
int listPosition(List* list, int value);

// проверяет наличие значения в списке
int listContain(List* list, int value);

// основная функция программы для работы со списком в диалоговом режиме
int main();
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Вы делаете "модуль", это объявление все портит. Надо выносить его в отдельный .c файл


#endif

78 changes: 78 additions & 0 deletions src/hw_6-1_sortList/hw_6-1_sortListMain.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
#include <stdio.h>
#include "hw_6-1_sortList.h"

// основная функция программы
int main()
{
List* list = listCreate();
int command;
int value;

printf("Программа для работы с сортированным списком\n");

do {
// вывод меню
printf("\nМеню операций:\n");
printf("0 - выйти\n");
printf("1 - добавить значение в сортированный список\n");
printf("2 - удалить значение из списка\n");
printf("3 - распечатать список\n");
printf("Выберите операцию: ");

scanf("%d", &command);

switch (command) {
case 0:
// выход из программы
printf("Завершение работы программы\n");
break;

case 1:
// добавление значения в сортированный список
printf("Введите значение для добавления: ");
if (scanf("%d", &value) != 1) {
printf("Ошибка, введите целое число");
// очистка буфера при ошибке
int temp;
while ((temp = getchar()) != '\n' && temp != EOF);
break;
}
// находим позицию для сохранения сортировки
int position = listPosition(list, value);
listInsert(list, position, value);

printf("Значение %d добавлено в позицию %d\n", value, position);
break;

case 2:
// удаление значения из списка
printf("Введите значение для удаления: ");
scanf("%d", &value);

// проверяем наличие значения в списке
int removePosition = listContain(list, value);
if (removePosition != -1) {
listRemove(list, removePosition);
printf("Значение %d удалено из списка\n", value);
} else {
printf("Значение %d не найдено в списке\n", value);
}
break;

case 3:
// печать списка
listPrint(list);
break;

default:
printf("Неизвестная команда, попробуйте снова\n");
break;
}

} while (command != 0);

// освобождение памяти перед выходом
listDelete(list);

return 0;
}