From 3b22e9c5e435c6c20fb0946370c8af6740a8b255 Mon Sep 17 00:00:00 2001 From: stutimohta20 <84969358+stutimohta20@users.noreply.github.com> Date: Mon, 7 Feb 2022 20:36:12 +0530 Subject: [PATCH] chore(CPlusPlus): add prefix to postfix stacks (#674) Co-authored-by: Ming Tsai <37890026+ming-tsai@users.noreply.github.com> Co-authored-by: Rahul Rajeev Pillai <66192267+Ashborn-SM@users.noreply.github.com> --- algorithms/CPlusPlus/README.md | 1 + .../CPlusPlus/Stacks/prefix_to_postfix.cpp | 64 +++++++++++++++++++ 2 files changed, 65 insertions(+) create mode 100644 algorithms/CPlusPlus/Stacks/prefix_to_postfix.cpp diff --git a/algorithms/CPlusPlus/README.md b/algorithms/CPlusPlus/README.md index 86bef265..e62faa25 100644 --- a/algorithms/CPlusPlus/README.md +++ b/algorithms/CPlusPlus/README.md @@ -88,6 +88,7 @@ - [Stack using Array](Stacks/stack-using-array.cpp) - [Infix to postfix expression conversion](Stacks/infix-to-postfix.cpp) - [Stock Span Problem using Stacks](Stacks/stock-span-problem.cpp) +- [Prefix to Postfix expression conversion](Stacks/prefix_to_postfix.cpp) ## Sorting diff --git a/algorithms/CPlusPlus/Stacks/prefix_to_postfix.cpp b/algorithms/CPlusPlus/Stacks/prefix_to_postfix.cpp new file mode 100644 index 00000000..6c59421f --- /dev/null +++ b/algorithms/CPlusPlus/Stacks/prefix_to_postfix.cpp @@ -0,0 +1,64 @@ +// Program to convert a prefix expression to postfix expression +// Prefix expression : An expression in which the operator appears before the operands. +// Postfix expression : An expression in which the operator appears after the operands. + + + +// Alogorithm +// To convert prefix to postfix expression we follow steps given below: +// Step 1. If the symbol is an operand, push it to the stack +// Step 2. If symbol is an operator then pop top two elements from stack +// Step 3. Then push an expression by concatenating (+op1+op2+symbol) +// Step 4. At last return the top element of stack as postfix expression + + + +// CODE: +#include +using namespace std; + +// Function to convert prefix to postfix expression +string prefix_to_postfix(string prefix) +{ + stack s; + // length of prefix expression + int l=prefix.length(); + + // Iterating through the Prefix expression from right to left + for(int i=l-1;i>=0;i--){ + // if the symbol is an operand, push it to the stack + if(prefix[i]>='a' && prefix[i]<='z'||prefix[i]>='A' && prefix[i]<='Z'){ + s.push(string(1,prefix[i])); + } + + // if symbol is an operator + else + { + string op1=s.top(); + s.pop(); + string op2=s.top(); + s.pop(); + string temp=(op1+op2+prefix[i]); + s.push(temp); + } + } + // returning element at top of stack + return s.top(); +} + +// MAIN FUNCTION +int main() +{ + string exp; + cout<<"Enter expression: "; + cin>>exp; + cout<<"Prefix to Postfix expression is: "<