-
Notifications
You must be signed in to change notification settings - Fork 0
Домашнее задание 6.1. Сортированный список. Разгуляева А.И. #5
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
ada1ra
wants to merge
6
commits into
main
Choose a base branch
from
hw_6-1_sortList
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
Show all changes
6 commits
Select commit
Hold shift + click to select a range
9895818
Add homework with sorted list
ada1ra 6add30d
Add -h file for sorted list
ada1ra 4497ede
Fix misspell in hw_6-1_sortList.h
ada1ra f648ff1
Replace main part to the separate file
ada1ra b9d7f27
Delete main part, struct declaration and rename listNew
ada1ra d3a9f1b
Rename listNew
ada1ra 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,159 @@ | ||
| #include "hw_6-1_sortList.h" | ||
| #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; | ||
| } | ||
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,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(); | ||
|
Collaborator
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. Вы делаете "модуль", это объявление все портит. Надо выносить его в отдельный .c файл |
||
|
|
||
| #endif | ||
|
|
||
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,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; | ||
| } |
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.
после include<>