-
Notifications
You must be signed in to change notification settings - Fork 0
Домашнее задание 5.2. Сортировочная станция. Разгуляева А.И. #3
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
9
commits into
main
Choose a base branch
from
hw_5-2_sortStation
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
9 commits
Select commit
Hold shift + click to select a range
bb1be3c
Add .c file with stack
ada1ra 9283e17
Add .h file with stack
ada1ra 6727967
Add .c file with homework
ada1ra 2badffb
Add .h file with homework
ada1ra aa92025
Add build instruction
ada1ra 54b2770
Updated stack.c with names changes according to WebKit
ada1ra a3a5e6d
Updated stack.h with names changes according to WebKit
ada1ra 19eebc4
Merge branch 'stack' into hw_5-2_sortStation
ada1ra 41ba8e9
Updated hw_5-2_sortStation.c with names changes according to WebKit a…
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,97 @@ | ||
| #include "hw_5-2_sortStation/hw_5-2_sortStation.h" | ||
| #include "stack/stack.h" | ||
| #include <ctype.h> | ||
| #include <stdio.h> | ||
| #include <stdlib.h> | ||
| #include <string.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 = 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++] = ' '; // добавляем пробел после числа | ||
| } | ||
| // если открывающая скобка, помещаем ее в стек | ||
| else if (current == '(') { | ||
| stackPush(infixStack, current); | ||
| } | ||
| // если закрывающая скобка.. | ||
| else if (current == ')') { | ||
| // извлекаем операторы из стека до открывающей скобки | ||
| while (infixStack != NULL && infixStack->top != NULL && stackPeek(infixStack) != '(') { | ||
| postfix[j++] = stackPop(infixStack); | ||
| postfix[j++] = ' '; | ||
| } | ||
| // удаляем открывающую скобку из стека | ||
| if (infixStack != NULL && infixStack->top != NULL && stackPeek(infixStack) == '(') { | ||
| stackPop(infixStack); | ||
| } | ||
| } | ||
| // если оператор (+, -, *, /).. | ||
| else if (current == '+' || current == '-' || current == '*' || current == '/') { | ||
| // извлекаем операторы с более высоким или равным приоритетом | ||
| while ((infixStack != NULL && infixStack->top != NULL) && precedence(stackPeek(infixStack)) >= precedence(current)) { | ||
| postfix[j++] = stackPop(infixStack); | ||
| postfix[j++] = ' '; | ||
| } | ||
| // помещаем текущий оператор в стек | ||
| stackPush(infixStack, current); | ||
| } | ||
| } | ||
|
|
||
| // извлекаем все оставшиеся операторы из стека | ||
| while (infixStack != NULL && infixStack->top != NULL) { | ||
| postfix[j++] = stackPop(infixStack); | ||
| postfix[j++] = ' '; | ||
| } | ||
|
|
||
| // завершаем строку | ||
| postfix[j] = '\0'; | ||
|
|
||
| // удаляем стек | ||
| stackDelete(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; | ||
| } |
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,13 @@ | ||
| #ifndef SORTSTATION_H | ||
|
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. По стайлгайду нужно использовать |
||
| #define SORTSTATION_H | ||
|
|
||
| // преобразование инфиксного выражения в постфиксное | ||
| void infixToPostfix(const char* infix, char* postfix); | ||
|
|
||
| // проверка приоритета операторов | ||
| int precedence(char op); | ||
|
|
||
| // ввод данных и вывод результата | ||
| int main(void); | ||
|
|
||
| #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,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. Программа выведет математическое выражение в постфиксной форме |
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,81 @@ | ||
| #include "stack.h" | ||
| #include <stdio.h> | ||
| #include <stdlib.h> | ||
|
|
||
| // создание пустого стека | ||
| Stack* stackNew(void) { | ||
| Stack* stack = (Stack*)malloc(sizeof(Stack)); | ||
| if (stack != NULL) { | ||
| stack->top = NULL; | ||
| } | ||
| return stack; | ||
| } | ||
|
|
||
| // добавление элемента на стек | ||
| int stackPush(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 stackPop(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 stackPeek(Stack* stack) { | ||
| if (stack == NULL || stack->top == NULL) { | ||
| printf("Stack is empty!\n"); | ||
| return -1; | ||
| } | ||
|
|
||
| return stack->top->data; | ||
| } | ||
|
|
||
| // удаление всего стека и освобождение памяти | ||
| void stackDelete(Stack* stack) { | ||
| if (stack == NULL) { | ||
| return; | ||
| } | ||
|
|
||
| // освобождаем все узлы | ||
| while (stack->top != NULL) { | ||
| Node* temp = stack->top; | ||
| stack->top = stack->top->next; | ||
| free(temp); | ||
| } | ||
|
|
||
| // освобождаем саму структуру стека | ||
| free(stack); | ||
| } |
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,29 @@ | ||
| #ifndef STACK_H | ||
| #define STACK_H | ||
|
|
||
| #include <stddef.h> | ||
|
|
||
| // максимальный размер стека | ||
| #define STACK_MAX_SIZE 100 | ||
|
|
||
| // структура узла стека | ||
| typedef struct Node { | ||
| int data; // целочисленные данные | ||
| struct Node* next; // указатель на следующий узел | ||
| } Node; | ||
|
|
||
| // структура стека | ||
| typedef struct { | ||
| Node* top; // указатель на вершину стека | ||
| } Stack; | ||
|
|
||
| // основные операции | ||
| int stackPush(Stack* stack, int value); // положить элемент на стек | ||
| int stackPop(Stack* stack); // взять элемент со стека | ||
| int stackPeek(Stack* stack); // посмотреть на элемент на вершине стека | ||
|
|
||
| // служебные функции | ||
| Stack* stackNew(void); // создать пустой стек | ||
| void stackDelete(Stack* stack); // удалить весь стек (освободить память) | ||
|
|
||
| #endif |
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.
Ваше решение абсолютно идентично с решением Александры Долженко. И я не преувеличиваю -- отличаются только имена переменных. Посмотрите сами: https://github.com/DolzhenkoAlexa/c_spbu/pull/4/files.
И тут Вам не повезло: Александра до этого ни разу не была замечена за списыванием, а к Вам с Алиной всегда были вопросы. Кстати, у Алины решение тоже подозрительно похоже: https://github.com/ialina07/homework-c/pull/4/files.
И не надо говорить, что это из-за того, что алгоритм один на всех: у остальных решения другие.
Так что Вам с Алиной -2 балла за эту задачу.
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.
у неё опубликовано решение позже меня, каким чудом я могла списать??
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.
А может, Вы с Алины списали? У неё основной коммит добавлен 16 октября в 21:56, а у Вас -- в 23:58.