Created
August 19, 2016 20:16
-
-
Save olegon/1828b6f0a1481f9feebaa42f3b3782d4 to your computer and use it in GitHub Desktop.
This file contains 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
#include <stdio.h> | |
#include <stdlib.h> | |
typedef char STACK_TYPE; | |
typedef struct { | |
int index; | |
int capacity; | |
STACK_TYPE *values; | |
} STACK; | |
STACK* stack_create(size_t capacity); | |
void stack_push(STACK *stack, STACK_TYPE value); | |
STACK_TYPE stack_pop(STACK *stack); | |
int stack_size(STACK *stack); | |
#define MAX_STRING_SIZE 1024 | |
int main (int argc, char *argv[]) { | |
char expression[MAX_STRING_SIZE], | |
finalExpression[MAX_STRING_SIZE], | |
*expPrt; | |
int i = 0; | |
STACK* operators; | |
if (argc == 2) { | |
expPrt = argv[1]; | |
} | |
else { | |
printf("Digite a expressão: "); | |
fflush(stdout); | |
scanf("%s%*c", expression); | |
expPrt = expression; | |
} | |
operators = stack_create(MAX_STRING_SIZE); | |
while (*expPrt != '\0') { | |
if (*expPrt == '^' | |
|| *expPrt == '*' | |
|| *expPrt == '/' | |
|| *expPrt == '+' | |
|| *expPrt == '-') { | |
stack_push(operators, *expPrt); | |
} | |
else if (*expPrt == ')') { | |
finalExpression[i++] = stack_pop(operators); | |
} | |
else if (*expPrt == '(') { | |
// ignore | |
} | |
else { | |
finalExpression[i++] = *expPrt; | |
} | |
if (stack_size(operators) < 0 || stack_size(operators) > MAX_STRING_SIZE) { | |
fprintf(stderr, "Expressão mal formada.\n"); | |
exit(EXIT_FAILURE); | |
} | |
expPrt++; | |
} | |
if (stack_size(operators) > 0) { | |
fprintf(stderr, "Expressão mal formada.\n"); | |
exit(EXIT_FAILURE); | |
} | |
printf("Expressão final: %s\n", finalExpression); | |
return 0; | |
} | |
STACK* stack_create(size_t capacity) { | |
STACK *stack = malloc(sizeof(STACK)); | |
if (stack == NULL) { | |
return NULL; | |
} | |
stack->values = malloc(sizeof(STACK_TYPE) * capacity); | |
if (stack->values == NULL) { | |
free(stack); | |
return NULL; | |
} | |
stack->index = 0; | |
stack->capacity = capacity; | |
return stack; | |
} | |
void stack_push(STACK *stack, STACK_TYPE value) { | |
stack->values[stack->index++] = value; | |
} | |
STACK_TYPE stack_pop(STACK *stack) { | |
return stack->values[--stack->index]; | |
} | |
int stack_size(STACK *stack) { | |
return stack->index; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment