-
Notifications
You must be signed in to change notification settings - Fork 1
/
Infix-Postfix-Conversion.c
102 lines (91 loc) · 2.55 KB
/
Infix-Postfix-Conversion.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
/*********************************************************************************************************************
* File : Infix-Postfix-Conversion.c
* Program : Program to implement conversion of expression from one notation to another - Infix to Postfix
* Language : C
* Author : Tom Sibu
* Version : 1.0
* Date : 09/11/2023
**********************************************************************************************************************/
#include <stdio.h>
#include <string.h>
void insert(char[],char,char[]);
int gpres(char);
int j=0,top=-1;
char infix[100], stack[100], postfix[100];
void main() {
int r=0;
printf("Enter the Infix expression:");
scanf("%s",infix);
while (infix[r]!='\0'){
if((infix[r]>='a'&&infix[r]<='z')||(infix[r]>='A'&&infix[r]<='Z')) {
postfix[j]=infix[r];
j++;
}
else if(infix[r]=='+' || infix[r]=='-' || infix[r]=='*' || infix[r]=='/' || infix[r]=='^' || infix[r]=='(' || infix[r]==')') {
insert(stack , infix[r] , postfix);
}
else if(infix[r]==' ') {
continue;
}
r++;
}
while (top != -1) {
postfix[j] = stack[top];
j++;
top--;
}
printf("Postfix expression: %s\n", postfix);
}
void insert(char stack[] , char k , char postfix[]) {
if (top==-1) {
top=0;
stack[top]=k;
}
else if(k=='(') {
top++;
stack[top]=k;
}
else if(k==')') {
while (stack[top]!='(') {
postfix[j]=stack[top];
j++;
top--;
}
top--;
}
else if(k=='^') {
top++;
stack[top]=k;
}
else {
if (stack[top]!='(') {
int c=gpres(k) ,e=stack[top], d=gpres(e);
while (c<=d && top!=-1) {
postfix[j]=stack[top];
top--;
j++;
d=gpres(stack[top]);
}
top++;
stack[top]=k;
}
else if(stack[top]=='(') {
top++;
stack[top]=k;
}
}
}
int gpres(char m){
if(m == '+')
return 1;
else if(m == '-')
return 1;
else if(m == '*')
return 2;
else if(m == '/')
return 2;
else if(m == '^')
return 3;
else if (m == '(')
return -1;
}