-
Notifications
You must be signed in to change notification settings - Fork 0
/
infix_to_Postfix.c
95 lines (87 loc) · 2.24 KB
/
infix_to_Postfix.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
// CONVERT INFIX EXPRESSION TO POSTFIX USING STACK
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX_SIZE 50
#define N 100
char s[MAX_SIZE];
int top = -1;
void pop(){
top--;
}
void push(char c){
top++;
s[top] = c;
}
char seekTop(){
if(top == -1){
printf("Stack is empty\nInvalid input infix expression !!\n");
exit(0);
}
return s[top];
}
void main(){
printf("Infix to Postfix convertion\n");
printf("Enter the infix expression: \n");
char infix[N];
scanf("%s",infix);
char c,temp;
push('(');
printf("\nPost fix expression: \n");
for(int i=0;i<strlen(infix);i++){
c = infix[i];
if(c == '('){
push(c);
}
else if(c == ')'){
while(seekTop() != '('){
printf("%c",seekTop());
pop();
}
pop();
}
else if(c == '+'){
while( seekTop() == '-' || seekTop() == '+' || seekTop() == '*' || seekTop() == '/' || seekTop() == '^' ){
printf("%c",seekTop());
pop();
}
push(c);
}
else if(c == '-'){
while(seekTop() == '+' || seekTop() == '-' || seekTop() == '*' || seekTop() == '/' || seekTop() == '^' ){
printf("%c",seekTop());
pop();
}
push(c);
}
else if(c == '/'){
while(seekTop() == '*' || seekTop() == '/' || seekTop() == '^' ){
printf("%c",seekTop());
pop();
}
push(c);
}
else if(c == '*'){
while(seekTop() == '/' || seekTop() == '*' || seekTop() == '^' ){
printf("%c",seekTop());
pop();
}
push(c);
}
else if(c == '^'){
push(c);
}
else{
printf("%c",c);
}
}
while(top > 0){
if(seekTop() == '('){
printf("\nUnbalanced paranthesis found\nInvalid input infix expression!!\n");
return;
}
printf("%c",seekTop());
pop();
}
printf("\n");
}