Question

In: Computer Science

Write the code for postfix expression in C++ using a linked stack that can take numbers...

Write the code for postfix expression in C++ using a linked stack that can take numbers bigger than 9 (any size the user gives) and pushes the final result onto the top of the stack

Solutions

Expert Solution

This is a updated code capable of taking integers greater than 9 (any size that user gives) for postfix expression evaluation

#include<iostream>
#include<stack>
#include<string>
#include<cmath>

using namespace std;


// Function to verify whether a character is numeric digit.
bool IsNumericDigit(char C)
{
        if(C >= '0' && C <= '9') return true;
        return false;
}



// Function to verify whether a character is operator symbol or not.
bool IsOperator(char C)
{
        if(C == '+' || C == '-' || C == '*' || C == '/' || C == '^')
                return true;

        return false;
}



// Function to perform an operation and return output.
int PerformOperation(char operation, int operand1, int operand2)
{
        if(operation == '+') return (operand1 + operand2);
        else if(operation == '-') return (operand1 - operand2);
        else if(operation == '*') return (operand1 * operand2);
        else if(operation == '/') return (operand1 / operand2);

        // Using typecasting for integer result for pow() function
        // The pow() function takes ‘double’ as the arguments and returns a ‘double’ value.
        // This function does not always work for integers. One such example is pow(5, 2).
    // When assigned to an integer, it outputs 24 on some compilers and works fine for some other compilers.
    // But pow(5, 2) without any assignment to an integer outputs 25.
        // To overcome this and output the accurate answer in integer format,
        // we can add 0.5 to the result and typecast it to int e.g (int)(pow(5, 2)+0.5) will give
        // the correct answer(25, in above example), irrespective of the compiler.

        else if(operation == '^') return ( (int)(pow(operand1, operand2) + 0.5) );

        else cout<<"Unexpected Error \n";
        return -1;
}



// Function to evaluate Postfix expression and return output
int EvaluatePostfix(string expression)
{
        // Declaring a Stack from Standard template library in C++.
        stack<int> S;

        for(int i = 0;i< expression.length();i++) {

                // Scanning each character from left.
                // If character is a delimitter, move on.
                if(expression[i] == ' ' || expression[i] == ',') continue;

                // If character is operator, pop two elements from stack, perform operation and push the result back.
                else if(IsOperator(expression[i])) {
                        // Pop two operands.
                        int operand2 = S.top(); S.pop();
                        int operand1 = S.top(); S.pop();
                        // Perform operation
                        int result = PerformOperation(expression[i], operand1, operand2);
                        //Push back result of operation on stack.
                        S.push(result);
                }
                else if(IsNumericDigit(expression[i])){
                        // Extract the numeric operand from the string
                        // Keep incrementing i as long as you are getting a numeric digit.
                        int operand = 0;
                        while(i<expression.length() && IsNumericDigit(expression[i])) {
                                // For a number with more than one digits, as we are scanning from left to right.
                                // Everytime , we get a digit towards right, we can multiply current total in operand by 10
                                // and add the new digit.
                                operand = (operand*10) + (expression[i] - '0');
                                i++;
                        }
                        // Finally, you will come out of while loop with i set to a non-numeric character or end of string
                        // decrement i because it will be incremented in increment section of loop once again.
                        // We do not want to skip the non-numeric character by incrementing i twice.
                        i--;

                        // Push operand on stack.
                        S.push(operand);
                }
        }
        // If expression is in correct format, Stack will finally have one element. This will be the output.
        return S.top();
}


int main()
{
        string expression;
        cout<<"Important instruction to be followed\n\nEvaluation Of postfix Expression in C++\nInput Postfix expression must be in a desired format.\nOperands must be integers and there should be space in between two operands.\nOnly '+'  ,  '-'  , '*' , '/' and '^'  operators are expected.";
        cout<<"\n\n\n\nEnter Postfix Expression: ";
        getline(cin,expression);
        int result = EvaluatePostfix(expression);
        cout<<"\n\nOutput = "<<result<<"\n";
        return 0;
}


Output screenshot


Related Solutions

Using a stack, write a program that turns a simple infix arithmetic expression into a postfix...
Using a stack, write a program that turns a simple infix arithmetic expression into a postfix expression. For example, 1 + 2 * 3 becomes 2 3 * 1 +. Also, evaluate the expression to ensure the expression is correct.
Using STL stack class, implement in C++ a function that converts an infix expression to postfix...
Using STL stack class, implement in C++ a function that converts an infix expression to postfix expression,
2. Convert the following infix form expression into the postfix form expression by using a stack:...
2. Convert the following infix form expression into the postfix form expression by using a stack: A+(B*(C-D)+E)/F-G*H Show the stack after each push/pop.
How to write code for stack with singly linked list using C? Please show examples for...
How to write code for stack with singly linked list using C? Please show examples for create, free, isempty, push, top, pop functions.
Find is the final result of evaluating the following postfix expression using a stack. Show each...
Find is the final result of evaluating the following postfix expression using a stack. Show each push and pop operation. 85 5 / 4 * 5   6 +   10    5 -   * +
CS 400 Assignment 4 Stack application: postfix expression evaluation. Description: - The stack data structure can...
CS 400 Assignment 4 Stack application: postfix expression evaluation. Description: - The stack data structure can be used to evaluate postfix expressions. Please refer to the first 14 pages of this tutorial for postfix expression evaluation: http://www.cs.nthu.edu.tw/~wkhon/ds/ds10/tutorial/tutorial2.pdf Requirement: - deal with single digit positive integers only. Operands and operators are fully separated by space. - learn and use STL stack: http://www.cplusplus.com/reference/stack/stack/ - learn and use isdigit(): http://www.cplusplus.com/reference/cctype/isdigit/ - take in a postfix arithmetic expression from cin, and evaluate its value....
IN C++ PLS COMMENT CODDEE, SO I CAN UNDERSTAND WHAT YOU DOING Stack application: postfix expression...
IN C++ PLS COMMENT CODDEE, SO I CAN UNDERSTAND WHAT YOU DOING Stack application: postfix expression evaluation. Description: - The stack data structure can be used to evaluate postfix expressions. Please refer to the first 14 pages of this tutorial for postfix expression evaluation: http://www.cs.nthu.edu.tw/~wkhon/ds/ds10/tutorial/tutorial2.pdf Requirement: - deal with single digit positive integers only. Operands and operators are fully separated by space. - learn and use STL stack: http://www.cplusplus.com/reference/stack/stack/ - learn and use isdigit(): http://www.cplusplus.com/reference/cctype/isdigit/ - take in a postfix...
Write a C++ code to insert the following numbers in two Linked Lists. Insert numbers of...
Write a C++ code to insert the following numbers in two Linked Lists. Insert numbers of first list in Linked List#1, and numbers of second list in Linked List#2. Do not insert both lists in a single Linked List. List#1. 5, 78, 45, 23, 11, 89, 10, 78, 6, 99, 876, 5, 67, 13 List#2. 5, 89, 688, 52, 557, 953, 5, 7, 55, 35, 89, 99, 99, 6, 557, 89, 5, 99, 6, 2, 45, 12, 7, 6, 94,...
using C++. edit this code down below so that it will implement stack with linked list...
using C++. edit this code down below so that it will implement stack with linked list contains a default constructor, a copy constructor, and a destructor. #include <iostream> #include <vector> #include <string> #include <stack> #include <limits> using namespace std; class Stack { public: bool isEmpty(); int top(); int pop(); void push(int); void printList(); private: vector<int> elements; }; bool Stack::isEmpty() { return elements.empty(); } int Stack::top() { if(isEmpty()) { throw runtime_error("error: stack is empty"); } return elements.back(); } int Stack::pop() {...
Solve this Write a C++ class that implements a stack using a linked list. The type...
Solve this Write a C++ class that implements a stack using a linked list. The type of data contained in the stack should be double. The maximum size of the stack is 30. Implement the following methods: . · Constructor and destructor; // 5 pts · void push (double value); // pushes an element with the value into the stack. 5 pts. · double pop (); // pops an element from the stack and returns its value. 5 pts. ·...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT