-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInfixToPostfix
More file actions
92 lines (82 loc) · 1.71 KB
/
InfixToPostfix
File metadata and controls
92 lines (82 loc) · 1.71 KB
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
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
#include<string.h>
#define MAX 11
int stack[MAX];
int top=-1;
void infixToPostfix(char infix[MAX],char postfix[MAX]);
int isOperator(int n);
int precedence(int n);
void push(int n);
int pop();
int main(){
char infix[MAX];
printf("\nEnter Infix expression : ");
gets(infix);
char postfix[MAX];
infixToPostfix(infix,postfix);
return 0;
}
void infixToPostfix(char infix[],char postfix[]){
int i=0,j=0,x;
int temp=infix[i];
push('(');
infix[MAX]=')';
while(temp!='\0'){
if(temp=='('){
push(temp);
}
else if(isalpha(temp) || isdigit(temp)){
postfix[j]=temp;
j++;
}else if(isOperator(temp)){
x=pop();
if(isOperator(temp) && precedence(x)>=precedence(temp)){
postfix[j]=x;
j++;
x=pop();
}
push(x);
push(temp);
}else if(temp==')'){
x=pop();
while(x!='('){
postfix[j]=x;
j++;
x=pop();
}
}
i++;
temp=infix[i];
}
printf("The postfix expression is : ");
for(int i=0;i<MAX-2;i++){
printf("%c",postfix[i]);
}
}
int isOperator(int n){
if( n=='*' || n=='*' || n=='/' || n=='+' || n=='-'){
return 1;
}else{
return 0;
}
}
int precedence(int n){
if(n=='/' || n=='*'){
return 2;
}else if(n=='+' || n=='-'){
return 1;
}else{
return 0;
}
}
void push(int n){
top++;
stack[top]=n;
}
int pop(){
int temp=stack[top];
top--;
return temp;
}