forked from siddhant3s/cs215
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathq8.c
76 lines (68 loc) · 1.51 KB
/
q8.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
/* PROGRAM TO CONVERT INFIX EXPRESSION TO POSTFIX EXPRESSION USING STACK */
#include<stdio.h>
#include<string.h>
/* MACRO FUNCTION TO CHECK WHETHER GIVEN CHARACTER IS AN OPERAND OR NOT */
#define operand(x) (x>='a' && x<='z' || x>='A' && x<='Z' || x>='0' && x<='9')
char infix[30],postfix[30],stack[30];
int top,i=0;
/* FUNCTION TO INITIALIZE THE STACK */
void init()
{
top=-1;
}
/* FUNCTION TO PUSH AN OPERATOR ON TO THE STACK */
void push(char x)
{
stack[++top]=x;
}
/* FUNCTION TO POP A CHARACTER STORED ONTO THE STACK */
char pop()
{
return(stack[top--]);
}
/* FUNCTION TO RETURN IN STACK PRIORITY OF A CHARACTER */
int isp(char x)
{
int y;
y=(x=='('?0:x=='^'?4:x=='*'?2:x=='/'?2:x=='+'?1:x=='-'?1:x==')'?6:-1);
return y;
}
/* FUNCTION TO RETURN INCOMING CHARACTER'S PRIORITY */
int icp(char x)
{
int y;
y=(x=='('?4:x=='^'?4:x=='*'?2:x=='/'?2:x=='+'?1:x=='-'?1:x==')'?6:-1);
return y;
}
/* FUNCTION TO CONVERT THE GIVEN INFIX TO PREFIX EXPRESSION */
void infixtopostfix()
{
int j,l=0;
char x,y;
stack[++top]='\0';
for (j=0; (x=infix[i++])!='\0'; j--)
if (operand(x))
postfix[l++]=x;
else
if (x==')')
while ((y=pop())!='(')
postfix[l++]=y;
else
{
while (isp(stack[top])>=icp(x))
postfix[l++]=pop();
push(x);
}
while (top>=0)
postfix[l++]=pop();
}
/* MAIN PROGRAM */
int main()
{
init();
printf("Enter an infix expression :\n");
scanf("%s",infix);
infixtopostfix();
printf("The resulting postfix expression is %s",postfix);
return 0;
} // End of main