forked from jake1412/Data-Structures-and-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
prefix_infix_postfix_stacks.c
executable file
·97 lines (81 loc) · 1.62 KB
/
prefix_infix_postfix_stacks.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
/*Program for infix, postfix and prefix using stack*/
#include<stdio.h>
#include<ctype.h>
#include<stdlib.h>
char infix[20],postfix[20];
char x;
int top=-1, s[30];
char y,c;
int MAX=30;
void push(int);
int pop();
int stop();
int priority(int);
int main()
{
int i,j=0;
printf("Enter the infix expression");
scanf("%s",infix);
i=0;
x=infix[i]; i++;
while(x!='#')
{
//printf("success");
if(isalpha(x)) { postfix[j]=x; j++;}
else if( x=='(')
push(x);
else if( x== ')')
{
c=pop();
while(c!='(') { postfix[j]=c; j++; c=pop(); }
}
else
{
if(priority(x) > priority(stop()) )
push(x);
else
{
while(priority(stop()) >= priority(x))
{ c=pop(); postfix[j]=c; j++;}
push(x);
}
}
x=infix[i]; i++;
} //end while
while(top>=0) { postfix[j]=pop(); j++; } //remaining expression from stack
printf("Postfix expression is: %s",postfix);
return 1;
}//end main
void push(int y)
{
if((top+1)==MAX) { printf("Stack Overflow"); exit(0); }
else
{
top++;
s[top]=y;
}
}
int pop()
{
int val;
if (top==-1) return -1;
else
{ val=s[top];
top--;
return val;
}
}
int stop()
{
if(top==-1) return -1;
else
return s[top];
}
int priority(int x)
{
if (x=='(') return 0;
else if ( x=='+' || x=='-') return 1;
else if ( x=='*' || x=='/' || x=='%') return 2;
else if (x=='^') return 3;
else return -1;
}