-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathinfixToPostfixUsingSTLStack.cpp
83 lines (77 loc) · 1.61 KB
/
infixToPostfixUsingSTLStack.cpp
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
#include <iostream>
#include <cstring>
#include <stack>
using namespace std;
int isOperand(char x)
{
if (x == '+' || x == '-' || x == '*' || x == '/' || x == '^' || x == '(' || x == ')')
return 0;
return 1;
}
int outPrecedence(char x)
{
if (x == '+' || x == '-')
return 1;
else if (x == '*' || x == '/')
return 3;
else if (x == '^')
return 6;
else if (x == '(')
return 7;
else if (x == ')')
return 0;
return -1;
}
int inPrecendence(char x)
{
if (x == '+' || x == '-')
return 2;
else if (x == '*' || x == '/')
return 4;
else if (x == '^')
return 5;
else if (x == ')')
return 0;
return -1;
}
char *Convert(char *infix)
{
char *postfix = new char[strlen(infix) + 1];
stack<char> stk;
int i = 0, j = 0;
while (infix[i] != '\0')
{
if (isOperand(infix[i]))
{
postfix[j++] = infix[i++];
}
else
{
if (stk.empty() || outPrecedence(infix[i]) > inPrecendence(stk.top()))
{
stk.push(infix[i++]);
}
else if (outPrecedence(infix[i]) > inPrecendence(stk.top()))
{
stk.pop();
}
else
{
postfix[j++] = stk.top();
stk.pop();
}
}
}
while (!stk.empty() && stk.top() != ')')
{
postfix[j++] = stk.top();
stk.pop();
return postfix;
}
}
int main()
{
char infix[] = "((a+b)*c)-d^e^f";
cout << Convert(infix) << endl;
return 0;
}