forked from matthewsamuel95/ACM-ICPC-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInfix to prefix conversion using stack.c
101 lines (97 loc) · 1.58 KB
/
Infix to prefix 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
#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],prefix[size],item;
char temp;
int i=0,j=0,len;
printf("enter infix expression\n");
gets(infix);
len=strlen(infix);
for(i=len;i>=0;i--)
{
item=infix[i];
if(item==')')
{
push(item);
}
else if(item>='a'&& item<='z'||item>='A'&& item<='Z')
{
prefix[j]=item;
j++;
}
else if(is_operator(item)==1)
{
temp=pop();
while(is_operator(temp)==1 && precendence(temp)>=precendence(item))
{
prefix[j]=temp;
j++;
temp=pop();
}
push(temp);
push(item);
}
else if(item=='(')
{
temp=pop();
while(temp!=')')
{
prefix[j]=temp;
j++;
temp=pop();
}
}
}
while(top>-1)
{
prefix[j]=pop();
j++;
}
prefix[j]='\0';
printf("the prefix expression is\n");
printf("%s",strrev(prefix));
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;
}