-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathpostfixeveal.c
118 lines (107 loc) · 2.12 KB
/
postfixeveal.c
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
107
108
109
110
111
112
113
114
115
116
117
118
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#define MAX 100
int stack[MAX], top = -1; // stack array and top
// Push function to insert element
void push(int data)
{
if (top == MAX - 1)
{
printf("\nStack overflow\n Aborting\n");
exit(0);
}
else
stack[++top] = data;
}
// Pop function to pop element
int pop()
{
int del;
if (top == -1)
{
printf("\nStack empty\n Invalid Expression\n");
exit(0);
}
else
{
del = stack[top--];
return del;
}
}
// Displays top element without popping it
int peek()
{
if(top == -1)
return -1;
else
return stack[top];
}
// debug
// To print elements of stack
void display()
{
if (top == -1)
printf("\nStack empty");
else
{
printf("\n");
for (int i = 0; i <= top; i++)
{
printf("%d, ", stack[i]);
}
}
}
// A utility function to check if
// the given character is operand
int isOperand(char ch)
{
return (isdigit(ch));
}
int evalPostfix( char exp[] )
{
for(int i=0; i<strlen(exp); i++)
{
if(isOperand(exp[i]))
{
// convert char to appropriate single-digit
push(exp[i]-'0');
}
else
{
int op2 = pop();
int op1 = pop();
int result;
switch(exp[i])
{
case '+':
result = op1+op2;
break;
case '-':
result = op1-op2;
break;
case '*':
result = op1*op2;
break;
case '/':
result = op1/op2;
break;
default:
printf("Unknown operator\n");
exit(0);
}
push(result);
}
}
return pop();
}
int main()
{
char exp[MAX]="23+";
printf("Enter a valid postfix expression: ");
scanf("%s",exp);
int result = evalPostfix(exp);
printf("Result : %d \n",result);
return 0;
}