-
Notifications
You must be signed in to change notification settings - Fork 2
/
postfixToInfix.c
95 lines (86 loc) · 1.41 KB
/
postfixToInfix.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
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAX 20
struct stackk{
char stack[MAX];
};
struct stackk s[MAX];
int top=-1;
int isFull();
int isEmpty();
void push(char*);
int isOperator(char);
int isOperand(char);
char *pop();
int main(){
char postfix[MAX],temp[2],op[2]={'(','\0'},cl[2]={')','\0'};
int i=0,j=0;
printf("Enter an postfix expression: ");
gets(postfix);
while(postfix[i]!='\0'){
char exp[MAX]={'\0'},op1[MAX]={'\0'},op2[MAX]={'\0'};
temp[0]=postfix[i];
temp[1]='\0';
if(isOperand(temp[0])){
push(temp);
}else if(isOperator(temp[0])){
strcpy(op2,pop());
strcpy(op1,pop());
strcat(exp,op);
strcat(exp,op1);
strcat(exp,temp);
strcat(exp,op2);
strcat(exp,cl);
push(exp);
}else{
printf("Invalid Arithmetic expression!\n");
exit(0);
}
i++;
}
printf("The infix expression is: ");
puts(s[0].stack);
}
void push(char *item){
if(isFull()){
printf("Overflow detected!\n");
}else{
top++;
strcpy(s[top].stack,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()){
exit(0);
}
return s[top--].stack;
}
int isOperand(char sym){
if(sym>='A'&&sym<='Z'||sym>='a'&&sym<='z'){
return 1;
}else{
return 0;
}
}