Skip to content

Instantly share code, notes, and snippets.

@oktavianto
Created March 31, 2019 08:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oktavianto/6c2bb13d892a4d97d8178e36d6e8fd42 to your computer and use it in GitHub Desktop.
Save oktavianto/6c2bb13d892a4d97d8178e36d6e8fd42 to your computer and use it in GitHub Desktop.
#include<bits/stdc++.h>
#include <conio.h>
using namespace std;
bool isOperator(char c)
{
return (!isalpha(c) && !isdigit(c));
}
int getPriority(char C)
{
if (C == '-' || C == '+')
return 1;
else if (C == '*' || C == '/')
return 2;
else if (C == '^')
return 3;
return 0;
}
string infixToPostfix(string infix)
{
infix = '(' + infix + ')';
int l = infix.size();
stack<char> char_stack;
string output;
for (int i = 0; i < l; i++) {
if (isalpha(infix[i]) || isdigit(infix[i]))
output += infix[i];
else if (infix[i] == '(')
char_stack.push('(');
else if (infix[i] == ')') {
while (char_stack.top() != '(') {
output += char_stack.top();
char_stack.pop();
}
char_stack.pop();
} else {
if (isOperator(char_stack.top())) {
while (getPriority(infix[i]) <= getPriority(char_stack.top())) {
output += char_stack.top();
char_stack.pop();
}
char_stack.push(infix[i]);
}
}
}
return output;
}
string infixToPrefix(string infix)
{
int l = infix.size();
reverse(infix.begin(), infix.end());
for (int i = 0; i < l; i++) {
if (infix[i] == '(') {
infix[i] = ')';
i++;
} else if (infix[i] == ')') {
infix[i] = '(';
i++;
}
}
string prefix = infixToPostfix(infix);
reverse(prefix.begin(), prefix.end());
return prefix;
}
int main()
{
char ulang;
string infix;
do {
system("cls");
cout << "Masukan infix: "; cin >> infix;
cout << "Prefix: "<<infixToPrefix(infix)<<endl;
cout << "Postfix: "<< infixToPostfix(infix)<<endl;
cout << "Ingin melanjutkan lagi? [y/n]"; cin >> ulang;
} while(ulang == 'y');
cout<<"Tidak mengulang dan terima kasih"<<endl;
getch();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment