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
136 changes: 136 additions & 0 deletions src/23oct25/sorting_station.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "../stack/stack.h"

int getPrecedence(char op)
{
if (op == '*' || op == '/') {
return 2;
}

if (op == '+' || op == '-') {
return 1;
}

return 0;
}

void infixToPostfix(const char* infix, char* postfix)
Copy link
Collaborator

Choose a reason for hiding this comment

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

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

Copy link
Collaborator

Choose a reason for hiding this comment

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

Кажется, здесь где-то не хватает обработки небалансных скобок

{
struct Stack* stack = new();
int i = 0;
int j = 0;
Comment on lines +23 to +24
Copy link
Collaborator

Choose a reason for hiding this comment

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

Переменные без внятного названия на верхнем уровне --- плохая идея. Что-нибудь типа prefixIdx и postfixIdx было бы сильно лучше

int topVal = 0;
int val = 0;
Comment on lines +25 to +26
Copy link
Collaborator

Choose a reason for hiding this comment

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

Во-первых, по-моему это должна быть одна переменная. А во-вторвых, лучше переменную объявлять по месту использования. Мало ли что там будет.


while (infix[i] != '\0') {
char token = infix[i];

if (isspace(token)) {
i++;
continue;
}

if (isdigit(token)) {
while (isdigit(infix[i])) {
postfix[j++] = infix[i++];
}
Comment on lines +37 to +39
Copy link
Collaborator

Choose a reason for hiding this comment

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

Интересное решение, кажется, даже числа заработают. Хотя просили только цифры

postfix[j++] = ' ';
continue;
}

if (token == '(') {
stack = push(stack, token);
} else if (token == ')') {
while (stack != NULL && peek(stack) != '(') {
stack = pop(stack, &topVal);
postfix[j++] = (char)topVal;
postfix[j++] = ' ';
}

if (stack != NULL && peek(stack) == '(') {
stack = pop(stack, &topVal);
}
} else if (token == '+' || token == '-' || token == '*' || token == '/') {
while (stack != NULL) {
int top = peek(stack);
if (top == '(') {
break;
}

if (getPrecedence((char)top) >= getPrecedence(token)) {
stack = pop(stack, &val);
postfix[j++] = (char)val;
postfix[j++] = ' ';
} else {
break;
}
}

stack = push(stack, token);
}

i++;
}

while (stack != NULL) {
stack = pop(stack, &val);
postfix[j++] = (char)val;
postfix[j++] = ' ';
}

if (j > 0 && postfix[j - 1] == ' ') {
postfix[j - 1] = '\0';
} else {
postfix[j] = '\0';
}

delete(stack);
}

int main(void)
{
char* infix = NULL;
char* postfix = NULL;
size_t capacity = 0;
size_t length = 0;
int ch = 0;

while ((ch = getchar()) != '\n' && ch != EOF) {
if (length + 1 >= capacity) {
if (capacity == 0) {
capacity = 16;
} else {
capacity *= 2;
}

infix = realloc(infix, capacity * sizeof(char));
if (infix == NULL) {
return 1;
}
}
infix[length++] = (char)ch;
}

if (infix != NULL) {
infix[length] = '\0';
} else {
infix = calloc(1, sizeof(char));
}

postfix = calloc(length * 2 + 1, sizeof(char));
if (postfix == NULL) {
free(infix);
return 1;
}

infixToPostfix(infix, postfix);
printf("%s\n", postfix);

free(infix);
free(postfix);

return 0;
}
53 changes: 53 additions & 0 deletions src/stack/stack.c
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)
{
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;

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;
}

void delete(struct Stack* stack)
{
while (stack != NULL) {
struct Stack* temp = stack;
stack = stack->next;
free(temp);
}
}

18 changes: 18 additions & 0 deletions src/stack/stack.h
Copy link
Collaborator

Choose a reason for hiding this comment

The 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);