forked from matthewsamuel95/ACM-ICPC-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInfix to postfix conversion using stack.c
108 lines (102 loc) · 1.69 KB
/
Infix to postfix conversion using stack.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
#include<stdio.h>
#include<string.h>
#define size 100
int top=-1;
char stack[size];
int is_operator(char symbol);
char pop();
void push(char item);
int precendence(char symbol);
int main()
{
char infix[size],postfix[size],item;
char temp;
int i=0,j=0;
printf("enter infix expression\n");
scanf("%s",infix);
while(infix[i]!='\0')
{
item=infix[i];
if(item=='(')
{
push(item);
}
else if(item>='a'&& item<='z'||item>='A'&& item<='Z')
{
postfix[j]=item;
j++;
}
else if(is_operator(item)==1)
{
temp=pop();
while(is_operator(temp)==1 && precendence(temp)>=precendence(item))
{
postfix[j]=temp;
j++;
temp=pop();
}
push(temp);
push(item);
}
else if(item==')')
{
temp=pop();
while(temp!='(')
{
postfix[j]=temp;
j++;
temp=pop();
}
}
else
{
printf("\n invalid\n");
exit(0);
}
i++;
}
while(top>-1) //for no paranthesis
{
postfix[j]=pop();
j++;
}
postfix[j]='\0';
printf("the postfix expression is\n");
printf("%s",postfix);
return 0;
}
void push(char item)
{
if(top>=size-1)
printf("stack overfloaw\n");
else
{
top++;
stack[top]=item;
}
}
int is_operator(char symbol)
{
if(symbol=='^'||symbol=='+'||symbol=='-'||symbol=='*'||symbol=='/')
return 1;
else
return 0;
}
char pop()
{
char item;
item=stack[top];
top--;
return item;
}
int precendence(char symbol)
{
if(symbol=='^')
return 3;
else if(symbol=='/'||symbol=='*')
return 2;
else if(symbol=='+'||symbol=='-')
return 1;
else
return 0;
}