-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHW01_stack.cpp
81 lines (74 loc) · 1.78 KB
/
HW01_stack.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
#include <stack>
#include <iostream>
using namespace std;
bool isOperator(char x)
{
return(x=='/'||x=='*'||x=='+'||x=='-'||x=='^');
}
bool isOperand(char x)
{
return(x!='*'&&x!='/'&&x!='+'&&x!='-'&&x!='('&&x!=')'&&x!='^');
}
template <typename T>
void printTheStack(stack<T> s)
{
stack<T> r;
while(!s.empty())
{
r.push(s.top());
s.pop();
}
while(!r.empty())
{
cout<<r.top()<<" ";
r.pop();
}
cout<<endl;
}
void InfixToPostfix(string formula)
{
stack<char> token;
stack<char> output;
for(int i=0; i<formula.length(); i++)
{
if(formula[i]=='(') token.push(formula[i]);
else if(isOperator(formula[i])) token.push(formula[i]);
else if(isOperand(formula[i])) output.push(formula[i]);
else{
output.push(token.top());
token.pop();
token.pop();
}
}
cout<<"Postfix: ";
printTheStack(output);
// cout<<"token: ";
// printTheStack(token);
if(token.empty()) cout<<"the token stack is empty! "<<endl;
else cout<<"the expression was not fully parenthesized! "<<endl;
}
void PostfixToInfix(string formula)
{
stack<string> myStack;
for(int i=0; i<formula.length(); i++)
{
if(isOperand(formula[i])) myStack.push(string(1, formula[i]));
else//if it's an operator
{
string operand1=myStack.top();
myStack.pop();
string operand2=myStack.top();
myStack.pop();
string newFormula="("+operand2+formula[i]+operand1+")";
myStack.push(newFormula);
}
}
//print the infix formula out
cout<<"Infix: ";
printTheStack(myStack);
}
int main()
{
// InfixToPostfix("(a-(b*2))");
PostfixToInfix("H42//E9//793/*561-+*+");
}