-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinfix_to_postfix.cpp
More file actions
90 lines (86 loc) · 1.82 KB
/
Copy pathinfix_to_postfix.cpp
File metadata and controls
90 lines (86 loc) · 1.82 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
#include <iostream>
#include <string.h>
#define MAX 15
using namespace std;
int top = -1, pos = 0;
char stack[MAX];
char infix[50] ;
char postfix[50];
int precedence(char op)
{
if (op == '+' || op == '-')
return 1; // Lowest precedence
if (op == '*' || op == '/')
return 2; // Higher precedence
}
char pop()
{
char data = stack[top];
top = top - 1;
return data;
}
void push(char x)
{
top = top + 1;
stack[top] = x;
}
int main()
{
// 33 to 47 operators ko ascii value
int i, a, b;
cout<<"Enter the expression: ";
cin>>infix;
int l = strlen(infix);
for (i = 0; i < l; i++)
{
if (infix[i] >= 33 && infix[i] <= 47)
{
if (infix[i] == '(')
{
push(infix[i]);
}
else if (infix[i] == ')')
{
while (stack[top] != '(')
{
char popped_op = pop();
postfix[pos] = popped_op;
pos++;
}
top = top - 1;
}
else
{
while (top > -1 && stack[top] != '(')
{
if (precedence(stack[top]) >= precedence(infix[i]))
{
char poped = pop();
postfix[pos] = poped;
pos++;
}
else
break;
}
push(infix[i]);
}
}
else
{
postfix[pos] = infix[i];
pos++;
}
}
if (top == -1)
cout << postfix;
else
{
while (top != -1)
{
postfix[pos] = pop();
pos++;
}
cout << postfix;
}
return 0;
}