-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathinfix2postfix
135 lines (116 loc) · 1.74 KB
/
infix2postfix
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
#include<iostream>
#include<string.h>
#include<stdio.h>
using namespace std;
#define MAX 100
char arr[MAX];
void push(char item);
char pop();
int precedence(char p);
void inftopfx( char source[], char target[]);
int top=-1;
/*------------------------------------------*/
int main()
{
int n;
char infix[100],postfix[100];
cout<<"Enter Infix Expression :\n";
gets(infix);
n=strlen(infix);
infix[n]=')';
infix[n+1]='\0';
inftopfx(infix,postfix);
cout<<"Corresponding Postfix Expression is :\n";
puts(postfix);
}
/*------------------------------------------*/
void push(char item)
{
if(top==MAX-1)
{
cout<<"OVERFLOW\n";
}
else
{
top=top+1;
arr[top]=item;
}
}
/*------------------------------------------*/
char pop()
{
char val;
val=arr[top];
top=top-1;
return val;
}
/*------------------------------------------*/
int precedence(char ch)
{
if(ch=='^')
{
return 3;
}
else if(ch=='*'||ch=='/')
{
return 2;
}
else if(ch=='+'||ch=='-')
{
return 1;
}
else
{
return 0;
}
}
/*------------------------------------------*/
void inftopfx(char source[], char target[])
{
int i=0,j=0,k=0;
char h[100];
push('(');
while(source[i]!='\0')
{
if(source[i]=='(')
{
push(source[i]);
i++;
}
else if(source[i]==')')
{
while(arr[top]!='(')
{
target[j++]=pop();
}
h[k++]=pop();
i++;
}
else if(source[i]>='a'&&source[i]<='z' || source[i]>='A'&&source[i]<='Z' )
{
target[j++]=source[i++];
}
else if(source[i]=='+' || source[i]=='-' || source[i]=='*' || source[i]=='/' || source[i]=='^' ||source[i]=='%' )
{
int g,h;
g=precedence(source[i]);
h=precedence(arr[top]);
if(g>h)
{
push(source[i++]);
}
else if(arr[top]=='(')
{
push(source[i++]);
}
else if(g<=h)
{
target[j++]=pop();
h=precedence(arr[top]);
push(source[i++]);
}
}
}
target[j]='\0';
}
/*------------------------------------------*/