-
Notifications
You must be signed in to change notification settings - Fork 0
/
postfix_calculate.cpp
106 lines (96 loc) · 1.9 KB
/
postfix_calculate.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
char *data;
int size;
int top;
} Stack;
Stack *stack;
char *postfix;
void initialize()
{
stack->data = (char *)malloc(sizeof(char));
stack->size = 1;
stack->top = -1;
if (stack->data != NULL)
{
for (int i = 0; i < stack->size; i++)
{
stack->data[i] = '\0';
}
}
}
void push(int value)
{
if (stack->top == stack->size)
{
stack->size *= 2;
stack->data = (char *)realloc(stack->data, sizeof(char) * stack->size);
}
stack->data[++stack->top] = value;
}
int pop()
{
if (stack->top == -1)
{
printf("empty");
return -1;
}
return stack->data[stack->top--];
}
void calculate()
{
int i = 0;
while (postfix[i] != '\0')
{
switch (postfix[i])
{
int data2;
int data1;
case '+':
data2 = pop();
data1 = pop();
push(data1 + data2);
break;
case '-':
data2 = pop();
data1 = pop();
push(data1 - data2);
break;
case '*':
data2 = pop();
data1 = pop();
push(data1 * data2);
break;
case '/':
data2 = pop();
data1 = pop();
push(data1 / data2);
break;
case '%':
data2 = pop();
data1 = pop();
push(data1 % data2);
break;
default:
push(postfix[i] - '0');
break;
}
i++;
}
printf("result-> %d", stack->data[stack->top]);
}
int main()
{
postfix = (char *)malloc(100);
stack = (Stack *)malloc(sizeof(Stack));
printf("input the postfix->");
initialize();
scanf("%s", postfix);
calculate();
free(stack->data);
free(stack);
free(postfix);
return 0;
}