-
Notifications
You must be signed in to change notification settings - Fork 0
Стек и очередь: Продвинутый баланс скобок #6
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
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,47 @@ | ||
| #include <stdio.h> | ||
| #include <stdbool.h> | ||
| #include <stdlib.h> | ||
| #include "../stack/stack.h" | ||
|
|
||
| bool isBalanced(const char* str) { | ||
| struct Stack* stack = new(); | ||
| bool balanced = true; | ||
|
|
||
| for (int i = 0; str[i] != '\0'; i++) { | ||
| char ch = str[i]; | ||
| if (ch == '(' || ch == '[' || ch == '{') { | ||
| stack = push(stack, ch); | ||
| } else if (ch == ')' || ch == ']' || ch == '}') { | ||
| if (stack == NULL) { | ||
| balanced = false; | ||
| break; | ||
| } | ||
|
|
||
| int top; | ||
| stack = pop(stack, &top); | ||
|
|
||
| if ((ch == ')' && top != '(') || (ch == ']' && top != '[') || (ch == '}' && top != '{')) { | ||
| balanced = false; | ||
| break; | ||
| } | ||
| } | ||
| } | ||
|
|
||
| if (stack != NULL) { | ||
| balanced = false; | ||
| delete(stack); | ||
| } | ||
|
|
||
| return balanced; | ||
| } | ||
|
|
||
| int main(void) { | ||
| const char* tests[] = {"()", "[]", "{}", "({})", "({)}", "((()))", "([{}])", "}{", "(", ")", ""}; | ||
| int numTests = sizeof(tests) / sizeof(tests[0]); | ||
|
|
||
| for (int i = 0; i < numTests; i++) { | ||
| printf("String: \"%s\" is %s\n", tests[i], isBalanced(tests[i]) ? "сбалансирована" : "не сбалансирована"); | ||
|
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. :) Интересный русско-английский у Вас вывод |
||
| } | ||
|
|
||
| return 0; | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,53 @@ | ||
| #include <stdlib.h> | ||
| #include "stack.h" | ||
|
|
||
| struct Stack { | ||
| int value; | ||
| struct Stack* next; | ||
| }; | ||
|
|
||
| struct Stack* push(struct Stack* stack, int value) | ||
|
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. Дизайн интересный, и был бы очень хорош в функциональном языке, но в Си приводит к ошибкам. Лучше сделать отдельную структуру для элемента стека и стуктуру-обёртку, которая будут передаваться в функции, тогда пользователю не нужно будет знать, что у него ничего о внутреннем устройстве стека |
||
| { | ||
| struct Stack* newStack = malloc(sizeof(struct Stack)); | ||
|
|
||
| if (!newStack) | ||
| return NULL; | ||
|
|
||
| newStack->value = value; | ||
| newStack->next = stack; | ||
| return newStack; | ||
| } | ||
|
|
||
| struct Stack* pop(struct Stack* stack, int* value) | ||
| { | ||
| if (stack == NULL) | ||
| return NULL; | ||
|
Comment on lines
+21
to
+24
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. Не лучшее решение. В такой реализации мы не отличим был ли пуст стек, или мы забрали последний элемент из него. Когда будете переписывать, Вам будет полезно знать про две стратегии реализации
|
||
|
|
||
| struct Stack* temp = stack->next; | ||
| *value = stack->value; | ||
| free(stack); | ||
| return temp; | ||
| } | ||
|
|
||
| int peek(struct Stack* stack) | ||
| { | ||
| if (stack == NULL) | ||
| return -1; | ||
|
|
||
| return stack->value; | ||
| } | ||
|
|
||
| struct Stack* new(void) | ||
| { | ||
| return NULL; | ||
| } | ||
|
Comment on lines
+40
to
+43
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. А правда в таком случае в этой функции вообще есть смысл? И, кстати, лучше не использовать |
||
|
|
||
| void delete(struct Stack* stack) | ||
| { | ||
| while (stack != NULL) { | ||
| struct Stack* temp = stack; | ||
| stack = stack->next; | ||
| free(temp); | ||
| } | ||
| } | ||
|
|
||
|
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. Вообще в задаче написано, что стек должен быть реализован в отдельной ветке, от которой отводятся другие две ветки. Это придётся сделать. |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,18 @@ | ||
| #pragma once | ||
|
|
||
| struct Stack; | ||
|
|
||
| // Создает новый стек с NULL | ||
| struct Stack* new(void); | ||
|
|
||
| // Кладет элемент на стек и возвращает измененный стек | ||
| struct Stack* push(struct Stack* stack, int value); | ||
|
|
||
| // Берет элемент со стек, возвращает измененный стек, сохраняет удаленное значение в аргумент value | ||
| struct Stack* pop(struct Stack* stack, int* value); | ||
|
|
||
| // Возвращает верхний элемент стека | ||
| int peek(struct Stack* stack); | ||
|
|
||
| // Удаляет весь стек | ||
| void delete(struct Stack* stack); |
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.
Кстати, это не по кодстайлу