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

set(CMAKE_C_STANDARD 17)

add_executable(counter
main.c
counter.c
)
55 changes: 55 additions & 0 deletions src/hw6_Lists/counter.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
#include <stdio.h>
#include <stdlib.h>
#include "counter.h"

struct ListOfWarriors* createList(int n)
{
struct ListOfWarriors* first = malloc(sizeof(struct ListOfWarriors)); // Создаем циклический список
first->position = 1;

struct ListOfWarriors* current = first;
for (int i = 2; i <= n; i++) {
current->next = malloc(sizeof(struct ListOfWarriors));
current = current->next;
current->position = i;
}
current->next = first; // Замыкаем круг в циклическом списке

return first;
}

void deleteWarrior(struct ListOfWarriors** current)
{
struct ListOfWarriors* toDelete = (*current)->next;
(*current)->next = toDelete->next;
free(toDelete);
*current = (*current)->next; // Переходим к следующему
}

int counter(int n, int m)

Choose a reason for hiding this comment

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

Лучше отдельно выделить функции для работы с циклическим списком.

{
if (n <= 0 || m <= 0) {
printf("Нельзя вводить отрицательные m, n\n");
return -1;
}

if (m == 1) {
return n; // Возвращаем нужный номер
}

struct ListOfWarriors* current = createList(n);

while (current->next != current) { //Пока не останется один воин (когда узел указывает сам на себя)
// Находим воина под номером m-1
for (int i = 1; i < m - 1; i++) {
current = current->next;
}

deleteWarrior(&current); // Удаляем следующего воина от найденного (то есть под номером m)
}

int neededPosition = current->position;
free(current);
return neededPosition; // Возвращаем нужный номер
}

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

struct ListOfWarriors {
int position;
struct ListOfWarriors* next;
};

// Функция создания циклического списка из n воинов
struct ListOfWarriors* createList(int n);

// Удаление война в списке
void deleteWarrior(struct ListOfWarriors** current);

int counter(int n, int m);
19 changes: 19 additions & 0 deletions src/hw6_Lists/main.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
#include <stdio.h>
#include "counter.h"

int main()
{
int n, m;
printf("Введите n и m: ");
scanf("%d %d", &n, &m);

int result = counter(n, m);

if (result != -1) {
printf("Нужная позиция: %d\n", result);
} else {
printf("Ошибка в вычислениях\n");
}

return 0;
}