Berikut codingnya :
#include <iostream>
#include <sstream>
#include <stack>
#include <limits>
#include <string>
using namespace std;
int a(char p)
{
int temp;
if (p=='^')
{
temp=1;
}
else if (p=='*'||p=='/')
{
temp=2;
}
else if (p=='+'||p=='/-')
{
temp=3;
}
return temp;
}
int main()
{
string infix;
cout<<"Input infix? = ";
getline(cin,infix);
stack<char>opr_stack;
stringstream postfix;
for (unsigned i=0;i<infix.length();i++)
{
if (infix[i]=='+'||infix[i]=='-'||infix[i]=='*'||infix[i]=='/'||infix[i]=='^')
{
while (!opr_stack.empty()&&a(opr_stack.top())<=a(infix[i]))
{
postfix<<opr_stack.top();
opr_stack.pop();
}
opr_stack.push(infix[i]);
}
else if (infix[i]=='(')
{
opr_stack.push(infix[i]);
}
else if (infix[i]==')')
{
while (opr_stack.top()!='(')
{
postfix<<opr_stack.top();
opr_stack.pop();
}
opr_stack.pop();
}
else
{
postfix<<infix[i];
}
}
while (!opr_stack.empty())
{
postfix<<opr_stack.top();
opr_stack.pop();
}
cout<<"Postfix = "<<postfix.str()<<endl;
cin.ignore(numeric_limits<streamsize>::max(),'\n');
return 0;
}
Preview :
Tidak ada komentar:
Posting Komentar