-
Notifications
You must be signed in to change notification settings - Fork 2
/
infixToPrefix.c
115 lines (104 loc) · 1.57 KB
/
infixToPrefix.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
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define MAX 20
char stack[MAX];
int top=-1;
int isFull();
int isEmpty();
void push(char);
int isOperator(char);
char pop();
int pre(char);
int main(){
char infix[MAX],prefix[MAX],item,temp;
int i=0,j=0;
printf("Enter an infix expression: ");
gets(infix);
strrev(infix);
while(infix[i]!='\0'){
item=infix[i];
if(item==')'){
push(item);
}else if(item>='A'&&item<='Z'||item>='a'&&item<='z'){
prefix[j]=item;
j++;
}else if(isOperator(item)){
temp=pop();
while(isOperator(temp)==1&&pre(temp)>=pre(item)){
prefix[j]=temp;
j++;
temp=pop();
}
push(temp);
push(item);
}else if(item=='('){
temp=pop();
while(temp!=')'){
prefix[j]=temp;
j++;
temp=pop();
}
}else{
printf("Invalid Arithmetix expression!\n");
exit(0);
}
i++;
}
while(!isEmpty()){
prefix[j]=pop();
j++;
}
prefix[j]='\0';
printf("The prefix expression is: ");
puts(strrev(prefix));
}
void push(char item){
if(isFull()){
printf("Overflow detected!\n");
}else{
top++;
stack[top]=item;
}
}
int isFull(){
if(top==MAX-1){
return 1;
}else{
return 0;
}
}
int isEmpty(){
if(top==-1){
return 1;
}else{
return 0;
}
}
int isOperator(char sym){
if(sym=='+'||sym=='-'||sym=='*'||sym=='/'||sym=='^'){
return 1;
}else{
return 0;
}
}
char pop(){
if(isEmpty()){
return '\0';
}
char ch;
ch=stack[top];
top--;
return ch;
}
int pre(char sym){
if(sym=='^'){
return 3;
}else if(sym=='*'||sym=='/'){
return 2;
}else if(sym=='+'||sym=='-'){
return 1;
}else{
return 0;
}
}