Skip to content

Commit b0819ea

Browse files
committed
added postfix evaluation in c
1 parent 17c9cfc commit b0819ea

File tree

3 files changed

+90
-0
lines changed

3 files changed

+90
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
#include <stdio.h>
2+
#define SIZE 100
3+
#include <math.h>
4+
#include <stdlib.h>
5+
/*my own stack*/
6+
int Stack[SIZE];
7+
int top = -1;
8+
int isEmpty()
9+
{
10+
return top == -1;
11+
}
12+
13+
void push(int item)
14+
{
15+
Stack[++top] = item;
16+
}
17+
18+
int pop()
19+
{
20+
if(isEmpty())
21+
{
22+
printf("STACK UNDERFLOW\n");
23+
exit(0);
24+
}
25+
int temp = Stack[top];
26+
top--;
27+
return temp;
28+
}
29+
30+
int evalPostfix(char *exp)
31+
{
32+
int i = 0;
33+
char str[50];
34+
int j = 0;
35+
//parsing
36+
while (exp[i] != '\0')
37+
{
38+
if (exp[i] >= '0' && exp[i] <= '9')
39+
{
40+
push(exp[i] - '0');
41+
}
42+
else //operator
43+
{
44+
if(isEmpty())
45+
{
46+
return -1;
47+
}
48+
int b = pop();
49+
int a = pop();
50+
int result = 0;
51+
switch (exp[i])
52+
{
53+
case '+':
54+
result = a + b;
55+
break;
56+
case '-':
57+
result = a - b;
58+
break;
59+
case '/':
60+
result = a / b;
61+
break;
62+
case '*':
63+
result = a * b;
64+
break;
65+
case '^':
66+
result = (int)pow(a, b);
67+
}
68+
push(result);
69+
}
70+
i++;
71+
}
72+
return Stack[top];
73+
}
74+
75+
int main()
76+
{
77+
char str[SIZE];
78+
printf("Enter the postfix expression\n");
79+
scanf("%s", str);
80+
int result = evalPostfix(str);
81+
printf("RESULT: %d\n", result);
82+
}

C/README.md

+1
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@
3636
* LINKED STACK
3737
* MISC
3838
* [Minimum bracket reversal for balanced expression](Data-Structures/STACKS/MISC-STACKS/minimum_bracket_reversal_for_balanced_expression.c)
39+
* [Postfix Evaluation](Data-Structures/STACKS/MISC-STACKS/postfix_evaluation.c)
3940

4041
#### HEAPS
4142

datastructures.md

+7
Original file line numberDiff line numberDiff line change
@@ -140,6 +140,13 @@ Indexer for Data Structures Lover
140140
* implementation
141141
* [C](C/Data-Structures/STACKS/MISC-STACKS/minimum_bracket_reversal_for_balanced_expression.c)
142142

143+
##### Postfix Evaluation
144+
145+
* blog
146+
* docs
147+
* implementation
148+
* [C](C/Data-Structures/STACKS/MISC-STACKS/postfix_evaluation.c)
149+
143150
##### TWO WAY STACK
144151

145152
* blog

0 commit comments

Comments
 (0)