-
Notifications
You must be signed in to change notification settings - Fork 2
/
InfixtoPostfix.c
102 lines (98 loc) · 1.59 KB
/
InfixtoPostfix.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
/*
C Program for convertix Infix expression to Postfix Expression
Author: Vivek K J
S3 CSA
*/
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define MAX_SIZE 100
// Global variables
char stack[MAX_SIZE];
char postfix[20];
int top=-1;
// Function to push
void push(char item){
if(top==MAX_SIZE-1){
printf("Stack Overflow");
}else{
top=top+1;
stack[top] = item;
}
}
// Function to pop
char pop(){
char item = stack[top];
top = top -1;
return item;
}
// Function to find Precedence
int precedence(char n){
switch(n){
case '^':
return 3;
break;
case '*':
case '/':
return 2;
break;
case '-':
case '+':
return 1;
break;
default:
return 0;
}
}
// Main function
void main(){
int i, j=0;
char infix[100];
printf("Enter Infix Expression: ");
scanf("%s", infix);
for(i=0; i<strlen(infix); i++){
switch(infix[i]){
case '(':
push(infix[i]);
break;
case ')':
while(stack[top] != '('){
postfix[j] = pop();
j++;
}
pop();
break;
case '+':
case '-':
case '*':
case '/':
case '^':
if(precedence(infix[i]) > precedence(stack[top])){
push(infix[i]);
}
else if(precedence(infix[i]) <= precedence(stack[top])){
if(infix[i] == '^')
{
push(infix[i]);
}
else{
while(precedence(infix[i]) <= precedence(stack[top])){
postfix[j] = pop();
j++;
}
push(infix[i]);
}
}
// else{
// postfix[j]=pop();
// j++;
// push(infix[i]);
// }
break;
default:
postfix[j]=infix[i];
j++;
}
}
printf("%s", postfix);
}