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
44 changes: 44 additions & 0 deletions 05_stack_and_queue/src/bracketsChecker.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
#include "stack.h"

#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int bracketsChecker(char* str, bool* res)
{
Stack* stack = newStack();
for (unsigned long i = 0; i < strlen(str); i++) {
if ((str[i] == '(') || (str[i] == '[') || (str[i] == '{')) {
push(stack, str[i]);
} else if ((str[i] == ')') || (str[i] == ']') || (str[i] == '}')) {
if (!isEmpty(stack)) {
char popped = pop(stack);
if (((str[i] == ')') && (popped != '(')) || ((str[i] == ']') && (popped != '[')) || ((str[i] == '}') && (popped != '{'))) {
*res = false;
}
} else {
*res = false;
}
}
Comment on lines +12 to +23

Choose a reason for hiding this comment

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

Minor: Я бы попробовал тут switch, но, вообще говоря, код в любом случае будто бы немного дублируется. Так что просто вкусовщина.

}
*res = *res && isEmpty(stack);
deleteStack(stack);
return 0;

Choose a reason for hiding this comment

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

Nit: немного странно, что получить не 0 нельзя. Хотя функция может привести к UB (например, если память закончилась).

}

int main(void)
{
int n = 0;
scanf("%d\n", &n);

char* input = calloc(n + 1, sizeof(char));
fgets(input, n + 1, stdin);

bool res = true;
bracketsChecker(input, &res);

Choose a reason for hiding this comment

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

Nit: а тут return code не проверяется.


printf("%d\n", res);
free(input);
return 0;
}
119 changes: 119 additions & 0 deletions 05_stack_and_queue/src/sortStation.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
#include "stack.h"

#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int getPriority(char operation)

Choose a reason for hiding this comment

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

Nit: обычно precedence вместо priority

{
if (operation == '*' || operation == '/') {
return 2;
} else if (operation == '+' || operation == '-') {
return 1;
}
return 0;
}

int sortStation(char* str, char* res)
{
unsigned lastUsedResIndex = 0;
Stack* stack = newStack();
unsigned long len = strlen(str);

Choose a reason for hiding this comment

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

Minor:

Suggested change
unsigned long len = strlen(str);
size_t len = strlen(str);

Ну это совсем придирка, просто strlen() отдает size_t, наверняка есть платформы, где unsigned long будет 32 бита, а size_t --- 64.

for (unsigned long i = 0; i < len; i++) {
if (isdigit(str[i])) {
if (lastUsedResIndex > 0 && res[lastUsedResIndex - 1] != ' ') {
res[lastUsedResIndex] = ' ';
lastUsedResIndex++;
}
while (i < len && isdigit(str[i])) {
res[lastUsedResIndex] = str[i];
lastUsedResIndex++;
i++;
}
if (i < len) {
i--;
}
Comment on lines +29 to +36

Choose a reason for hiding this comment

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

Есть у меня некоторые подозрения, что можно было написать вот так:

Suggested change
while (i < len && isdigit(str[i])) {
res[lastUsedResIndex] = str[i];
lastUsedResIndex++;
i++;
}
if (i < len) {
i--;
}
res[lastUsedResIndex] = str[i];
lastUsedResIndex++;

И поведение было бы такое же. Ну в смысле -- нет необходимости во вложенном цикле. Но это так -- с первого взгляда.

А то с этим сдвигом влево не совсем понятно выходит, что происходит.

} else if ((str[i] == '+') || (str[i] == '-') || (str[i] == '*') || (str[i] == '/')) {
while (!isEmpty(stack)) {
char peeked = peek(stack);
if (peeked == '(') {
break;
}
if (getPriority(peeked) >= getPriority(str[i])) {
if (lastUsedResIndex > 0 && res[lastUsedResIndex - 1] != ' ') {
res[lastUsedResIndex] = ' ';
lastUsedResIndex++;
}
res[lastUsedResIndex] = pop(stack);
lastUsedResIndex++;
} else {
break;
}
}
push(stack, str[i]);
} else if (str[i] == '(') {
push(stack, str[i]);
} else if (str[i] == ')') {
char peeked = 0;
if (isEmpty(stack)) {
deleteStack(stack);
return 1;
}
Comment on lines +59 to +62

Choose a reason for hiding this comment

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

Minor: одно из немногих мест, когда я бы рассмотрел goto. Так легче "не забыть почистить память". Ну и строк меньше.

    if (isEmpty(stack)) goto error;
    
    // ...
    error:
    deleteStack(stack);
    return 1;

А вот в Go это бы сделал defer :)

peeked = peek(stack);
while (peeked != '(') {
if (lastUsedResIndex > 0 && res[lastUsedResIndex - 1] != ' ') {
res[lastUsedResIndex] = ' ';
lastUsedResIndex++;
}
res[lastUsedResIndex] = peeked;
lastUsedResIndex++;
pop(stack);

if (isEmpty(stack)) {
deleteStack(stack);
return 1;
}
peeked = peek(stack);
}
pop(stack);
}
}
while (!isEmpty(stack)) {
char popped = pop(stack);
if (popped == '(') {
deleteStack(stack);
return 1;
}
if (lastUsedResIndex > 0 && res[lastUsedResIndex - 1] != ' ') {
res[lastUsedResIndex] = ' ';
lastUsedResIndex++;
}
res[lastUsedResIndex] = popped;
lastUsedResIndex++;
}
res[lastUsedResIndex] = '\0';
deleteStack(stack);
return 0;
}

int main(void)
{
int n = 0;
scanf("%d\n", &n);

char* input = calloc(n + 1, sizeof(char));
fgets(input, n + 1, stdin);

char* res = calloc(n + 1, sizeof(char));

if (sortStation(input, res) == 0) {
printf("%s\n", res);
} else {
printf("Входная строка некорректна");
}

free(input);
free(res);
return 0;
}
64 changes: 64 additions & 0 deletions 05_stack_and_queue/src/stack.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
#include "stack.h"
#include <stdbool.h>
#include <stdlib.h>

typedef struct StackNode {
char data;
struct StackNode* next;
} StackNode;

typedef struct Stack {
StackNode* head;
} Stack;

Stack* newStack(void)
{
Stack* stack = calloc(1, sizeof(Stack));
return stack;
}

bool isEmpty(Stack* stack)
{
return stack->head == NULL;
}

void push(Stack* stack, char data)
{
StackNode* element = (StackNode*)calloc(1, sizeof(StackNode));

Choose a reason for hiding this comment

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

Nit: конечно, calloc() может не сработать, это лучше бы учитывать и проверять, что вызов вернул не NULL.


element->data = data;
element->next = stack->head;
stack->head = element;
}

char pop(Stack* stack)
{
if (isEmpty(stack)) {
return '\0';
}

StackNode* oldNode = stack->head;
char data = oldNode->data;
stack->head = stack->head->next;
Comment on lines +36 to +42

Choose a reason for hiding this comment

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

Minor: нетривиальные предположения лучше помещать в assert()

Suggested change
if (isEmpty(stack)) {
return '\0';
}
StackNode* oldNode = stack->head;
char data = oldNode->data;
stack->head = stack->head->next;
if (isEmpty(stack)) {
return '\0';
}
assert(stack->head != NULL);
StackNode* oldNode = stack->head;
char data = oldNode->data;
stack->head = stack->head->next;


free(oldNode);

return data;
}

char peek(Stack* stack)
{
if (isEmpty(stack)) {
return '\0';
}

return stack->head->data;
}

void deleteStack(Stack* stack)
{
while (!isEmpty(stack)) {
pop(stack);
}
free(stack);
}
Comment on lines +58 to +64

Choose a reason for hiding this comment

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

Nit: обычно функции удаления хорошо делать устойчивыми к NULL входам.

Suggested change
void deleteStack(Stack* stack)
{
while (!isEmpty(stack)) {
pop(stack);
}
free(stack);
}
void deleteStack(Stack* stack)
{
if (stack == NULL) return;
while (!isEmpty(stack)) {
pop(stack);
}
free(stack);
}

11 changes: 11 additions & 0 deletions 05_stack_and_queue/src/stack.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
#pragma once
#include <stdbool.h>

typedef struct Stack Stack;

Stack* newStack(void);
bool isEmpty(Stack*);
void push(Stack* stack, char data);
char pop(Stack* stack);
char peek(Stack* stack);
void deleteStack(Stack* stack);