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
8 changes: 8 additions & 0 deletions src/Test2Rewrite/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
cmake_minimum_required(VERSION 3.25)

project(Project C)

add_compile_options(-Wall -Wextra -Wpedantic)

add_executable(task2 task2.c)
add_executable(task3 list.c)
270 changes: 270 additions & 0 deletions src/Test2Rewrite/list.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,270 @@
#include "list.h"
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>

typedef struct ListNode ListNode;

struct ListNode {
int value;
struct ListNode* next;
};

struct List {
ListNode* head;
};

List* newList()
{
List* list = calloc(1, sizeof(*list));
return list;
}

bool insert(List* list, int index, int value)
{
if (list == NULL || index < 0) {
return false;
}
if (index == 0) {
ListNode* newNode = malloc(sizeof(ListNode));
newNode->value = value;
newNode->next = list->head;
list->head = newNode;
return true;
}
ListNode* current = list->head;
int counter = 0;
while (current != NULL) {
if (counter == index - 1) {
ListNode* newNode = malloc(sizeof(ListNode));
newNode->value = value;
newNode->next = current->next;
current->next = newNode;
return true;
}
current = current->next;
counter++;
}
return false;
}
int get(List* list, int index)
{
if (list == NULL || isEmpty(list) || index < 0)
return -1;
Comment on lines +52 to +53
Copy link
Collaborator

Choose a reason for hiding this comment

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

Неа, очень плохо, у Вас код ошибки --- элемент области допустимых значений

if (index == 0) {
return list->head->value;
}
ListNode* current = list->head;
int counter = 0;
while (current != NULL) {
if (counter == index) {
return current->value;
}
current = current->next;
counter++;
}
return -1;
}

bool removeElement(List* list, int index)
{
if (list == NULL || isEmpty(list) || index < 0) {
return false;
}
ListNode* current = list->head;
if (index == 0) {
list->head = current->next;
free(current);
return true;
}
int counter = 0;
while (current != NULL) {
if (counter == index - 1) {
if (current->next == NULL)
return false;
ListNode* nodeToDelete = current->next;
current->next = nodeToDelete->next;
free(nodeToDelete);
return true;
}
current = current->next;
counter++;
}
return false;
}

bool deleteList(List* list)
{
if (list == NULL || isEmpty(list)) {
return false;
}
while (!isEmpty(list)) {
removeElement(list, 0);
}
free(list);
return true;
}

void printList(List* list)
{
if (list == NULL || isEmpty(list)) {
printf("Список пустой\n");
return;
}
ListNode* current = list->head;
while (current != NULL) {
printf("%d ", current->value);
current = current->next;
}
printf("\n");
}

bool isEmpty(List* list) { return list->head == NULL; }

int getLength(List* list)
{
if (list == NULL || isEmpty(list)) {
return -1;
}
int counter = 0;
ListNode* current = list->head;
do {
counter++;
current = current->next;
} while (current != NULL);
return counter;
}

bool oneElement(List* list) { return list->head->next == NULL; }

/*
Эта функция копирования спика
на вход принимает два списка и копирует один в другой
*/
void copy(List* listToCopy, List* listToPut)
{
int length = getLength(listToCopy);
int element = 0;
for (int i = 0; i < length; i++) {
element = get(listToCopy, i);
insert(listToPut, i, element);
}
}

List* reverse(List* list)
{
if (list == NULL || isEmpty(list)) {
return NULL;
}

List* newOneList = newList();
copy(list, newOneList);

if (newOneList == NULL || isEmpty(newOneList)) {
return NULL;
}
ListNode* prev = NULL;
ListNode* current = newOneList->head;
ListNode* next = NULL;

while (current != NULL) {
next = current->next;
current->next = prev;
prev = current;
current = next;
}
newOneList->head = prev;
return newOneList;
}
Comment on lines +154 to +178
Copy link
Collaborator

Choose a reason for hiding this comment

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

Похоже на правду, но доставая элементы из первого списка и перекладывая их во второй было бы сильно проще


bool testReverse()
{
List* list1 = newList();
insert(list1, 0, 1);
insert(list1, 1, 2);
insert(list1, 2, 3);
List* newOne1 = reverse(list1);
int arr[3] = { 3, 2, 1 };
int* p = arr;
for (int i = 0; i < 3; i++) {
if (get(newOne1, i) != p[i]) {
deleteList(list1);
deleteList(newOne1);
return false;
Comment on lines +192 to +193
Copy link
Collaborator

Choose a reason for hiding this comment

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

А здесь никакого сообщения об ошибке нет, странно

}
}
deleteList(list1);
deleteList(newOne1);

List* list2 = newList();
insert(list2, 0, 3);
insert(list2, 1, 2);
insert(list2, 2, 1);
List* newOne2 = reverse(list2);
int arr2[3] = { 1, 2, 3 };
int* p2 = arr2;
for (int i = 0; i < 3; i++) {
if (get(newOne2, i) != p2[i]) {
deleteList(list2);
deleteList(newOne2);
printf("Сломалось на стандартной проверке\n");
return false;
}
}
deleteList(list2);
deleteList(newOne2);

List* list3 = newList();
insert(list3, 0, 1);
List* newOne3 = reverse(list3);
if (get(newOne3, 0) != 1) {
printf("Сломалось на списке из одного элемента\n");
deleteList(list3);
deleteList(newOne3);
return false;
}
deleteList(list3);
deleteList(newOne3);

List* list4 = newList();
List* newOne4 = reverse(list4);
if (newOne4 != NULL) {
deleteList(list4);
deleteList(newOne4);
printf("Сломалось на пустом изначальном списке\n");
return false;
}
deleteList(list4);
deleteList(newOne4);

List* list5 = newList();
insert(list5, 0, 1);
insert(list5, 1, 1);
insert(list5, 2, 1);
List* newOne5 = reverse(list5);
int arr5[3] = { 1, 1, 1 };
int* p5 = arr5;
for (int i = 0; i < 3; i++) {
if (get(newOne5, i) != p5[i]) {
deleteList(list5);
deleteList(newOne5);
printf("Сломалось на проверке из одинаковых элементов\n");
return false;
}
}
deleteList(list5);
deleteList(newOne5);

return true;
}

int main()
{
bool isOk = testReverse();
if (!isOk) {
printf("Некоторые тесты не прошли\n");
} else {
printf("Все тесты прошли успешно!\n");
}
return 0;
}
81 changes: 81 additions & 0 deletions src/Test2Rewrite/list.h
Copy link
Collaborator

Choose a reason for hiding this comment

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

Офигеть! Столько функций на контрольной пугает...

Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
#pragma once
#include <stdbool.h>

// структура содержащая указатель на список
typedef struct List List;

/*
* функция создания нового списка
* ничего не принимает
* возвращает указатель на объект типа List
*/
List* newList();

/*
* функция вставки элемента по заданному индексу
* принимает на вход указатель на список, желаемый индекс и значение
* возвращает булевое значение, сообщающее, удачно ли прошла операция
*/
bool insert(List* list, int index, int value);

/*
* функция просмотра элемента списка по индексу
* принимает указатель на список и индекс
* возвращает value элемента
* если что-то пошло не так, вернет -1
*/
int get(List* list, int index);

/*
* функция удаления элемента по индексу
* принимает указатель на список и индекс элемента
* возвращает булевое значние, сообщающее, удачно ли прошла операция
* внутри себя освобождает память удаляемого элемента
*/
bool removeElement(List* list, int index);
Comment on lines +29 to +35
Copy link
Collaborator

Choose a reason for hiding this comment

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

Не нужна


/*
* функция удаления всего списка
* принимает указатель на список
* внутри себя вызывает функцию removeElement
* возвращает булевое значение, удачно ли прошла операция
*/
bool deleteList(List* list);

/*
* функция вывода списка в консоль
* принимает только указаетль на список
* ничего не возвращает
* печатает элементы списка через пробел
* в случае переданного пустого или несуществующего списка сообщает об этом пользователю
*/
void printList(List* list);
Comment on lines +45 to +52
Copy link
Collaborator

Choose a reason for hiding this comment

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

Не нужна


/*
* функция проверки, пустой ли список
* возвращает true если пустой, false, если нет
* на вход принимает указатель на список
*/
bool isEmpty(List* list);

/*
* функция, возвращающая длину списка
* принимает на вход указатель на список
* проходится по всем элементам
* возвращает его длину
*/
int getLength(List* list);

/*
* функция проверки, один ли элемент в списке
* возвращает true если да, false, если нет
* на вход принимает указатель на список
*/
bool oneElement(List* list);
Comment on lines +70 to +74
Copy link
Collaborator

Choose a reason for hiding this comment

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

Не нужна


/*
* Функция переворачивания списка
* на вход принимает указатель на список, который надо перевернуть
* возвращает указатель на новый список, в котором элементы в перевернутом состоянии
*/
List* reverse(List* list);
Loading