From bb1be3c46bccbd2ad73879607b158b8bc08f6240 Mon Sep 17 00:00:00 2001 From: ada1ra Date: Thu, 16 Oct 2025 23:52:21 +0300 Subject: [PATCH 1/8] Add .c file with stack --- src/stack/stack.c | 81 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 81 insertions(+) create mode 100644 src/stack/stack.c diff --git a/src/stack/stack.c b/src/stack/stack.c new file mode 100644 index 0000000..b974dbe --- /dev/null +++ b/src/stack/stack.c @@ -0,0 +1,81 @@ +#include "stack.h" +#include +#include + +// создание пустого стека +Stack* stack_new(void) { + Stack* stack = (Stack*)malloc(sizeof(Stack)); + if (stack != NULL) { + stack->top = NULL; + } + return stack; +} + +// добавление элемента на стек +int stack_push(Stack* stack, int value) { + if (stack == NULL) { + printf("Stack is NULL!\n"); + return -1; + } + + // создаем новый узел + Node* new_node = (Node*)malloc(sizeof(Node)); + if (new_node == NULL) { + printf("Memory failed!\n"); + return -1; + } + + // заполняем узел + new_node->data = value; + new_node->next = stack->top; + + // обновляем вершину стека + stack->top = new_node; +} + +// взятие элемента со стека +int stack_pop(Stack* stack) { + if (stack == NULL || stack->top == NULL) { + printf("Stack is empty!\n"); + return -1; + } + + // сохраняем данные из вершины + Node* temp = stack->top; + int value = temp->data; + + // перемещаем вершину на следующий элемент + stack->top = stack->top->next; + + // освобождаем память удаляемого узла + free(temp); + + return value; +} + +// просмотр элемента на вершине стека +int stack_peek(Stack* stack) { + if (stack == NULL || stack->top == NULL) { + printf("Stack is empty!\n"); + return -1; + } + + return stack->top->data; +} + +// удаление всего стека и освобождение памяти +void stack_delete(Stack* stack) { + if (stack == NULL) { + return; + } + + // освобождаем все узлы + while (stack->top != NULL) { + Node* temp = stack->top; + stack->top = stack->top->next; + free(temp); + } + + // освобождаем саму структуру стека + free(stack); +} \ No newline at end of file From 9283e17122827ea97373dcab073aeff1077f9bcd Mon Sep 17 00:00:00 2001 From: ada1ra Date: Thu, 16 Oct 2025 23:52:30 +0300 Subject: [PATCH 2/8] Add .h file with stack --- src/stack/stack.h | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 src/stack/stack.h diff --git a/src/stack/stack.h b/src/stack/stack.h new file mode 100644 index 0000000..08fee91 --- /dev/null +++ b/src/stack/stack.h @@ -0,0 +1,29 @@ +#ifndef STACK_H +#define STACK_H + +#include + +// максимальный размер стека +#define STACK_MAX_SIZE 100 + +// структура узла стека +typedef struct Node { + int data; // целочисленные данные + struct Node* next; // указатель на следующий узел +} Node; + +// структура стека +typedef struct { + Node* top; // указатель на вершину стека +} Stack; + +// основные операции +int stack_push(Stack* stack, int value); // положить элемент на стек +int stack_pop(Stack* stack); // взять элемент со стека +int stack_peek(Stack* stack); // посмотреть на элемент на вершине стека + +// служебные функции +Stack* stack_new(void); // создать пустой стек +void stack_delete(Stack* stack); // удалить весь стек (освободить память) + +#endif \ No newline at end of file From 6727967c6a1ef63c6044404eca13524aa6237a3d Mon Sep 17 00:00:00 2001 From: ada1ra Date: Thu, 16 Oct 2025 23:58:42 +0300 Subject: [PATCH 3/8] Add .c file with homework --- src/hw_5-2_sortStation/hw_5-2_sortStation.c | 97 +++++++++++++++++++++ 1 file changed, 97 insertions(+) create mode 100644 src/hw_5-2_sortStation/hw_5-2_sortStation.c diff --git a/src/hw_5-2_sortStation/hw_5-2_sortStation.c b/src/hw_5-2_sortStation/hw_5-2_sortStation.c new file mode 100644 index 0000000..e1f4f98 --- /dev/null +++ b/src/hw_5-2_sortStation/hw_5-2_sortStation.c @@ -0,0 +1,97 @@ +#include +#include +#include +#include +#include "stack\stack.h" +#include "hw_5-2_sortStation\hw_5-2_sortStation.h" + +// определение приоритета операторов +int precedence(char oper) { + if (oper == '+' || oper == '-') { + return 1; + } else if (oper == '*' || oper == '/') { + return 2; + } + return 0; +} + +// преобразование инфиксного выражения в постфиксное +void infixToPostfix(const char* infix, char* postfix) { + Stack* infixStack = stack_new(); // создаем стек для операторов + int j = 0; // индекс для записи в выходную строку + + // проходим по каждому символу входной строки + for (int i = 0; infix[i] != '\0'; i++) { + char current = infix[i]; + + // если пробел, пропускаем + if (current == ' ') { + continue; + } + + // если цифра, добавляем в выходную строку + if (isdigit(current)) { + postfix[j++] = current; + postfix[j++] = ' '; // добавляем пробел после числа + } + // если открывающая скобка, помещаем ее в стек + else if (current == '(') { + stack_push(infixStack, current); + } + // если закрывающая скобка.. + else if (current == ')') { + // извлекаем операторы из стека до открывающей скобки + printf("1"); + while (infixStack != NULL && stack_peek(infixStack) != '(') { + postfix[j++] = stack_pop(infixStack); + postfix[j++] = ' '; + } + // удаляем открывающую скобку из стека + printf("2"); + if (infixStack != NULL && stack_peek(infixStack) == '(') { + stack_pop(infixStack); + } + } + // если оператор (+, -, *, /).. + else if (current == '+' || current == '-' || current == '*' || current == '/') { + printf("3"); + // извлекаем операторы с более высоким или равным приоритетом + while ((infixStack != NULL) && precedence(stack_peek(infixStack)) >= precedence(current)) { + postfix[j++] = stack_pop(infixStack); + postfix[j++] = ' '; + } + // помещаем текущий оператор в стек + stack_push(infixStack, current); + } + } + + // извлекаем все оставшиеся операторы из стека + while (infixStack != NULL) { + postfix[j++] = stack_pop(infixStack); + postfix[j++] = ' '; + } + + // завершаем строку + postfix[j] = '\0'; + + // удаляем стек + stack_delete(infixStack); +} + +int main() { + char infix[100]; + char postfix[100]; + + printf("Введите инфиксное выражение (например, (1 + 1) * 2): "); + fgets(infix, sizeof(infix), stdin); + + // удаляем символ новой строки, если он есть + infix[strcspn(infix, "\n")] = 0; + + // преобразуем в постфиксную запись + infixToPostfix(infix, postfix); + + printf("Постфиксная запись: %s\n", postfix); + + return 0; +} \ No newline at end of file From 2badffbc401764eb7081674f24b9bff155e1f6a2 Mon Sep 17 00:00:00 2001 From: ada1ra Date: Thu, 16 Oct 2025 23:58:48 +0300 Subject: [PATCH 4/8] Add .h file with homework --- src/hw_5-2_sortStation/hw_5-2_sortStation.h | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 src/hw_5-2_sortStation/hw_5-2_sortStation.h diff --git a/src/hw_5-2_sortStation/hw_5-2_sortStation.h b/src/hw_5-2_sortStation/hw_5-2_sortStation.h new file mode 100644 index 0000000..99daf53 --- /dev/null +++ b/src/hw_5-2_sortStation/hw_5-2_sortStation.h @@ -0,0 +1,13 @@ +#ifndef SORTSTATION_H +#define SORTSTATION_H + +// преобразование инфиксного выражения в постфиксное +void infixToPostfix(const char* infix, char* postfix); + +// проверка приоритета операторов +int precedence(char op); + +// ввод данных и вывод результата +int main(void); + +#endif \ No newline at end of file From aa9202526c3c80c6a83e4d2a1d66babdbf364a58 Mon Sep 17 00:00:00 2001 From: ada1ra Date: Thu, 16 Oct 2025 23:59:03 +0300 Subject: [PATCH 5/8] Add build instruction --- src/hw_5-2_sortStation/instruction.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 src/hw_5-2_sortStation/instruction.md diff --git a/src/hw_5-2_sortStation/instruction.md b/src/hw_5-2_sortStation/instruction.md new file mode 100644 index 0000000..95c6f50 --- /dev/null +++ b/src/hw_5-2_sortStation/instruction.md @@ -0,0 +1,17 @@ +# Инструкция по сборке + +Домашнее задание 5.2 Сортировочная станция + +1. Откройте терминал и перейдите в директорию с файлами приложения (hw_5-2_sortStation) +2. Выполните команду компиляции: +```console +gcc hw_5-2_sortStation.c ../stack/stack.c -I.. -o hw_5-2_sortStation +``` +3. Запустите программу: +```console +./hw_5-2_sortStation +``` +### Использование +1. Введите строку с математическим выражением в инфиксной форме (не более 100 чисел) +2. Нажмите Enter для завершения ввода +3. Программа выведет математическое выражение в постфиксной форме \ No newline at end of file From 54b2770e96e4289e4ab21eccb9f57146bcda0d0e Mon Sep 17 00:00:00 2001 From: ada1ra Date: Thu, 23 Oct 2025 22:09:27 +0300 Subject: [PATCH 6/8] Updated stack.c with names changes according to WebKit --- src/stack/stack.c | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/stack/stack.c b/src/stack/stack.c index b974dbe..caec476 100644 --- a/src/stack/stack.c +++ b/src/stack/stack.c @@ -3,7 +3,7 @@ #include // создание пустого стека -Stack* stack_new(void) { +Stack* stackNew(void) { Stack* stack = (Stack*)malloc(sizeof(Stack)); if (stack != NULL) { stack->top = NULL; @@ -12,7 +12,7 @@ Stack* stack_new(void) { } // добавление элемента на стек -int stack_push(Stack* stack, int value) { +int stackPush(Stack* stack, int value) { if (stack == NULL) { printf("Stack is NULL!\n"); return -1; @@ -34,7 +34,7 @@ int stack_push(Stack* stack, int value) { } // взятие элемента со стека -int stack_pop(Stack* stack) { +int stackPop(Stack* stack) { if (stack == NULL || stack->top == NULL) { printf("Stack is empty!\n"); return -1; @@ -54,7 +54,7 @@ int stack_pop(Stack* stack) { } // просмотр элемента на вершине стека -int stack_peek(Stack* stack) { +int stackPeek(Stack* stack) { if (stack == NULL || stack->top == NULL) { printf("Stack is empty!\n"); return -1; @@ -64,7 +64,7 @@ int stack_peek(Stack* stack) { } // удаление всего стека и освобождение памяти -void stack_delete(Stack* stack) { +void stackDelete(Stack* stack) { if (stack == NULL) { return; } From a3a5e6de1b9ea18b840504042404de93fa92b1d3 Mon Sep 17 00:00:00 2001 From: ada1ra Date: Thu, 23 Oct 2025 22:09:37 +0300 Subject: [PATCH 7/8] Updated stack.h with names changes according to WebKit --- src/stack/stack.h | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/stack/stack.h b/src/stack/stack.h index 08fee91..7951dc1 100644 --- a/src/stack/stack.h +++ b/src/stack/stack.h @@ -18,12 +18,12 @@ typedef struct { } Stack; // основные операции -int stack_push(Stack* stack, int value); // положить элемент на стек -int stack_pop(Stack* stack); // взять элемент со стека -int stack_peek(Stack* stack); // посмотреть на элемент на вершине стека +int stackPush(Stack* stack, int value); // положить элемент на стек +int stackPop(Stack* stack); // взять элемент со стека +int stackPeek(Stack* stack); // посмотреть на элемент на вершине стека // служебные функции -Stack* stack_new(void); // создать пустой стек -void stack_delete(Stack* stack); // удалить весь стек (освободить память) +Stack* stackNew(void); // создать пустой стек +void stackDelete(Stack* stack); // удалить весь стек (освободить память) #endif \ No newline at end of file From 41ba8e98325e519a56ecff06ecc2c119d58ec735 Mon Sep 17 00:00:00 2001 From: ada1ra Date: Thu, 23 Oct 2025 23:34:55 +0300 Subject: [PATCH 8/8] Updated hw_5-2_sortStation.c with names changes according to WebKit and fix error --- src/hw_5-2_sortStation/hw_5-2_sortStation.c | 70 ++++++++++----------- 1 file changed, 35 insertions(+), 35 deletions(-) diff --git a/src/hw_5-2_sortStation/hw_5-2_sortStation.c b/src/hw_5-2_sortStation/hw_5-2_sortStation.c index e1f4f98..1ab107d 100644 --- a/src/hw_5-2_sortStation/hw_5-2_sortStation.c +++ b/src/hw_5-2_sortStation/hw_5-2_sortStation.c @@ -1,12 +1,13 @@ +#include "hw_5-2_sortStation/hw_5-2_sortStation.h" +#include "stack/stack.h" +#include #include #include #include -#include -#include "stack\stack.h" -#include "hw_5-2_sortStation\hw_5-2_sortStation.h" // определение приоритета операторов -int precedence(char oper) { +int precedence(char oper) +{ if (oper == '+' || oper == '-') { return 1; } else if (oper == '*' || oper == '/') { @@ -16,82 +17,81 @@ int precedence(char oper) { } // преобразование инфиксного выражения в постфиксное -void infixToPostfix(const char* infix, char* postfix) { - Stack* infixStack = stack_new(); // создаем стек для операторов - int j = 0; // индекс для записи в выходную строку - +void infixToPostfix(const char* infix, char* postfix) +{ + Stack* infixStack = stackNew(); // создаем стек для операторов + int j = 0; // индекс для записи в выходную строку + // проходим по каждому символу входной строки for (int i = 0; infix[i] != '\0'; i++) { char current = infix[i]; - + // если пробел, пропускаем if (current == ' ') { continue; } - + // если цифра, добавляем в выходную строку if (isdigit(current)) { postfix[j++] = current; - postfix[j++] = ' '; // добавляем пробел после числа + postfix[j++] = ' '; // добавляем пробел после числа } // если открывающая скобка, помещаем ее в стек else if (current == '(') { - stack_push(infixStack, current); + stackPush(infixStack, current); } // если закрывающая скобка.. else if (current == ')') { // извлекаем операторы из стека до открывающей скобки - printf("1"); - while (infixStack != NULL && stack_peek(infixStack) != '(') { - postfix[j++] = stack_pop(infixStack); + while (infixStack != NULL && infixStack->top != NULL && stackPeek(infixStack) != '(') { + postfix[j++] = stackPop(infixStack); postfix[j++] = ' '; } // удаляем открывающую скобку из стека - printf("2"); - if (infixStack != NULL && stack_peek(infixStack) == '(') { - stack_pop(infixStack); + if (infixStack != NULL && infixStack->top != NULL && stackPeek(infixStack) == '(') { + stackPop(infixStack); } } // если оператор (+, -, *, /).. else if (current == '+' || current == '-' || current == '*' || current == '/') { - printf("3"); // извлекаем операторы с более высоким или равным приоритетом - while ((infixStack != NULL) && precedence(stack_peek(infixStack)) >= precedence(current)) { - postfix[j++] = stack_pop(infixStack); + while ((infixStack != NULL && infixStack->top != NULL) && precedence(stackPeek(infixStack)) >= precedence(current)) { + postfix[j++] = stackPop(infixStack); postfix[j++] = ' '; } // помещаем текущий оператор в стек - stack_push(infixStack, current); + stackPush(infixStack, current); } } - + // извлекаем все оставшиеся операторы из стека - while (infixStack != NULL) { - postfix[j++] = stack_pop(infixStack); + while (infixStack != NULL && infixStack->top != NULL) { + postfix[j++] = stackPop(infixStack); postfix[j++] = ' '; } - + // завершаем строку postfix[j] = '\0'; - + // удаляем стек - stack_delete(infixStack); + stackDelete(infixStack); } -int main() { +int main() +{ char infix[100]; char postfix[100]; - + printf("Введите инфиксное выражение (например, (1 + 1) * 2): "); fgets(infix, sizeof(infix), stdin); - + // удаляем символ новой строки, если он есть infix[strcspn(infix, "\n")] = 0; - + // преобразуем в постфиксную запись infixToPostfix(infix, postfix); - + printf("Постфиксная запись: %s\n", postfix); - + return 0; -} \ No newline at end of file +}