Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #define _CRT_SECURE_NO_WARNINGS
- #include <stdio.h>
- #include <malloc.h>
- #include <stdbool.h>
- #include <string.h>
- #include <ctype.h>
- char postfix_str[1001] = { 0 }; //the reason why i lost 2 weeks
- //stack_begin
- struct list
- {
- char data;
- struct list * next;
- };
- typedef struct stack
- {
- struct list *top;
- } stack;
- stack *construct()
- {
- stack *_stack;
- _stack = (stack*)malloc(sizeof(stack));
- _stack->top = NULL;
- return _stack;
- }
- void push(stack *_stack, int a)
- {
- struct list *p;
- p = (struct list *) malloc(sizeof(struct list));
- p->data = a;
- p->next = _stack->top;
- _stack->top = p;
- }
- char top(stack *_stack)
- {
- return (_stack->top->data);
- }
- int is_empty(stack *_stack)
- {
- if (_stack->top == NULL)
- return 1;
- return 0;
- }
- char pop(stack *_stack)
- {
- char a;
- struct list *p;
- p = _stack->top;
- a = p->data;
- _stack->top = p->next;
- free(p);
- return a;
- }
- //stack_end
- int get_priority(char symbol)
- {
- char operations[] = "()+-*/";
- for (size_t priority = 0; operations[priority] != '\0'; priority++)
- {
- if (symbol == operations[priority])
- return priority / 2;
- }
- return -1;
- }
- char *to_postfix(char infix_str[])
- {
- int priority = 0;
- stack *postfix_stack = construct();
- int j = 0;
- for (int i = 0; infix_str[i] != '\0'; i++)
- {
- priority = get_priority(infix_str[i]);
- if (priority == -1)
- {
- postfix_str[j++] = infix_str[i];
- continue;
- }
- if (infix_str[i] == '(')
- {
- push(postfix_stack, infix_str[i]);
- continue;
- }
- if (infix_str[i] == ')')
- {
- while (top(postfix_stack) != '(')
- {
- postfix_str[j++] = pop(postfix_stack);
- }
- pop(postfix_stack);
- continue;
- }
- while (is_empty(postfix_stack) == 0 && priority <= get_priority(top(postfix_stack)))
- {
- postfix_str[j++] = pop(postfix_stack);
- }
- push(postfix_stack, infix_str[i]);
- }
- while (is_empty(postfix_stack) == 0)
- {
- postfix_str[j++] = pop(postfix_stack);
- }
- free(postfix_stack);
- return postfix_str;
- }
- int main()
- {
- freopen("input.txt", "r", stdin);
- freopen("output.txt", "w", stdout);
- char in_str[1001] = { 0 };
- gets_s(in_str, 1001);
- printf("%s", to_postfix(in_str));
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement