stack assignment
stack assignment
infix to postfix
#include<iostream>
#include<stack>
using namespace std;
int prec(char c)
{
if (c == '^')
return 3;
else if (c == '/' || c == '*')
return 2;
else if (c == '+' || c == '-')
return 1;
else
return -1;
}
void infixToPostfix(string s)
{
stack<char> st;
string result;
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')
|| (c >= '0' && c <= '9'))
result += c;
else if (c == '(')
st.push('(');
else if (c == ')') {
while (st.top() != '(') {
result += st.top();
st.pop();
}
st.pop();
}
else {
while (!st.empty()
&& prec(s[i]) <= prec(st.top())) {
result += st.top();
st.pop();
}
st.push(c);
}
}
while (!st.empty()) {
result += st.top();
st.pop();
}
int main()
{
string exp = "a+b*(c^d-e)";
infixToPostfix(exp);
return 0;
}
Output : abcd^e-*+
Infix to Prefix
#include <algorithm>
#include <iostream>
#include <stack>
using namespace std;
int prec(char c)
{
if (c == '^')
return 3;
else if (c == '/' || c == '*')
return 2;
else if (c == '+' || c == '-')
return 1;
else
return -1;
}
string infixToPrefix(string s)
{
stack<char> st;
string result;
reverse(s.begin(), s.end());
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >=
'0' && c <= '9'))
result += c;
else if (c == ')')
st.push(c);
else if (c == '(') {
while (!st.empty() && st.top() != ')') {
result += st.top();
st.pop();
}
st.pop();
} else {
while (!st.empty() && prec(s[i]) < prec(st.top())) {
result += st.top();
st.pop();
}
st.push(c);
}
}
while (!st.empty()) {
result += st.top();
st.pop();
}
reverse(result.begin(), result.end());
return result;
}
int main()
{
string exp = "a+b*(c^d-e)";
Output:
+a*b-^cde