Question

In: Computer Science

Please Use the STL library for this question and Should be done in C++ and Provide...

Please Use the STL library for this question and Should be done in C++ and Provide screenshots of the OUTPUT

Topic: Stack

Infix to postfix conversion
        Take Input mathematical expression in infix notation, and convert it into a postfix
notation. The infix notation may or may not have round parenthesis.

Postfix expression evaluation
        Take Input mathematical expression in postfix form, evaluate it, and display the result

The mathematical expression can contain
Numbers as operands (numbers can be of single or multiple digits)
Operators (+ , - , * , / , ^ )
Round parenthesis
^ exponent operator

In postfix notation, operands should be separated from each other with a space to avoid any
confusion. For example (32 – 4) when converted to postfix notation should NOT be written as
324-, but as 32 4 -

Solutions

Expert Solution

/* C++ implementation to convert infix expression to postfix*/
// Note that here we use std::stack for Stack operations STL library
#include<bits/stdc++.h>
using namespace std;

//Function to return precedence of operators
int prec(char c)
{
   if(c == '^')
   return 3;
   else if(c == '*' || c == '/')
   return 2;
   else if(c == '+' || c == '-')
   return 1;
   else
   return -1;
}


int evaluatePostfix(char* exp)
{
//cout<<exp;
// Create a stack of capacity equal to expression size
std::stack<int> st;
int i;
  
// See if stack was created successfully
  
// Scan all characters one by one
for (i = 0; exp[i]; ++i)
{
// If the scanned character is an operand (number here),
// push it to the stack.
if (isdigit(exp[i]))
st.push(exp[i] - '0');
  
// If the scanned character is an operator, pop two
// elements from stack apply the operator
else
{   
int val1 = st.top();
st.pop();
int val2 = st.top();
st.pop();
switch (exp[i])
{
case '+': st.push(val2 + val1); break;
case '-': st.push(val2 - val1); break;
case '*': st.push(val2 * val1); break;
case '/': st.push(val2/val1); break;
}
}
}
return st.top();
}

// The main function to convert infix expression
//to postfix expression
void infixToPostfix(string s)

{
// cout<<"kk";
   std::stack<char> st;
   st.push('N');
   int l = s.length();
   string ns;
   int i;
   string postfix_exp;
   char char_array[l + 1];
   //cout<<"gg";
  
   for(int i = 0; i < l; i++)
  
   { // cout<<i;
       // If the scanned character is an operand, add it to output string.
       if((s[i] >= '0' && s[i] <= '9')) {
       ns=ns+" "+s[i];
       postfix_exp = postfix_exp+s[i];
}
       // If the scanned character is an ‘(‘, push it to the stack.
       else if(s[i] == '(')
      
       st.push('(');
      
       // If the scanned character is an ‘)’, pop and to output string from the stack
       // until an ‘(‘ is encountered.
       else if(s[i] == ')')
       {
           while(st.top() != 'N' && st.top() != '(')
           {
               char c = st.top();
               st.pop();
           ns =ns+" "+ c;
           postfix_exp = postfix_exp+c;
           }
           if(st.top() == '(')
           {
               char c = st.top();
               st.pop();
           }
       }
      
       //If an operator is scanned
       else{
           while(st.top() != 'N' && prec(s[i]) <= prec(st.top()))
           {
               char c = st.top();
               st.pop();
               ns =ns+" "+ c;
               postfix_exp = postfix_exp+c;
           }
           st.push(s[i]);
       }

   }
   //Pop all the remaining elements from the stack
   while(st.top() != 'N')
   {
       char c = st.top();
       st.pop();
       ns = ns+ " "+c;
       postfix_exp = postfix_exp+c;
   }
  
   cout << ns << endl;

   strcpy(char_array, postfix_exp.c_str());

   cout<<"postfix evaluation: "<< evaluatePostfix(char_array);

}

//Driver program to test above functions
int main()
{
   string exp = "3+4*5/6";

   infixToPostfix(exp);
   return 0;
}

Hope i helped you.



Related Solutions

TO BE DONE IN C LANGUAGE BEFORE READING THE QUESTION PLEASE NOTE THAT YOUR FUNCTION SHOULD...
TO BE DONE IN C LANGUAGE BEFORE READING THE QUESTION PLEASE NOTE THAT YOUR FUNCTION SHOULD EXACTLY PRODUCE THE GIVEN OUTPUT AND THE TIME COMPLEXITY SHOULD BE O(N^2) YOU NEED TO KNOW ABOUT COCKTAIL SHAKER SORT ALGORITHM: Cocktail-shaker sort is a modification of Bubble sort. Cocktail-shaker sort traverses the data structure in one direction, pushing the largest element ahead towards one end of the data structure, and then in the opposite direction, pushing the smallest element towards the other end,...
C++ PROJECT Create a sudoku game that involves the following concepts: STL library. (Maps, Sets, Lists,...
C++ PROJECT Create a sudoku game that involves the following concepts: STL library. (Maps, Sets, Lists, Stacks and Queues), with Iterators and Algorithms Show especially Especially Algorithm/Iterators/Containers in the STL Minimum of 900 lines Include Full documentation
c++ problem: Use an STL stack to reverse a line of input characters that are read...
c++ problem: Use an STL stack to reverse a line of input characters that are read into a string. Your stack should contain the characters of the user's string. Use getline() for input – it needs to be part of your C++ tool inventory. A note on getline: Suppose I am doing the following - This program reverses a string using the STL stack Enter your string of less than 80 characters followed by an ENTER a string input Enter...
Please write code in c++. Use iostream (and any string library if you need it). Create...
Please write code in c++. Use iostream (and any string library if you need it). Create s structure plane : First line contains n(0 < n < 1001). Then n lines inputed in given format:   First - ID[int type]   Second - FromLocation[char*]   Third - ToLocation[char*]   Fourth - DepartureTime[char*] Output: Sorted list of planes should be in UPPER CASE. Example of input:(it's just one of an examples, you need to write code generally) 10 40 Shuch Satp 05:47 89 Kyzy Taldy  07:00...
Three studies done on obesity please provide reference
Three studies done on obesity please provide reference
in c++, please provide only a function. the function should be named "tally." it takes no...
in c++, please provide only a function. the function should be named "tally." it takes no parameters but returns an int. the first int should be 0, next being 1, then 2, etc.. will rate if correct. again should only be 1 function.
In C++ please. 6. Define a callback. Name three types of callbacks used in STL algorithms....
In C++ please. 6. Define a callback. Name three types of callbacks used in STL algorithms. Given an container that contains integers. myCont Use count_if() algorithm and a lambda function as a callback to count the number of integers that are even. Explain the operation of your code.
Matrix Multiplication with Threads - C/C++ In this assignment you will use the Pthreads library to...
Matrix Multiplication with Threads - C/C++ In this assignment you will use the Pthreads library to write a program that multiplies two square arrays and compare the difference between the imperative and parallel implementations of this algorithm. Use the matrix mulltiplication algorithm. Write a program that contains three functions: (1) A function that has an integer as a parameter and returns a pointer to square array of integers (i.e. both dimensions should be equal). The function should allocate storage from...
MUST BE DONE IN C (NOT C++) This program should utilize the basics of strings. First,...
MUST BE DONE IN C (NOT C++) This program should utilize the basics of strings. First, declare and initialize a string. You can name the variable whichever way you want and you can initialize it to whichever value you want. Then, use a for loop to print its characters; one at a time, until you reach the null character. After this, go ahead and declare a second string (since you are not initializing it right away, you will have to...
C++ on randomly generated integers stored in vectors. you will use routines from STL <algorithm> to...
C++ on randomly generated integers stored in vectors. you will use routines from STL <algorithm> to implement these algorithms. Using the following functions with their description const int DATA_SIZE = 200; const int SEARCH_SIZE = 100; const int DATA_SEED = 7; const int SEARCH_SEED = 9; void genRndNums( vector<int>& v, int seed ) { This routine generates random integers in the range [ LOW = 1, HIGH =200 ] and puts them in vector v. Initializes the random number generator...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT