Question

In: Computer Science

Q5 - 15 pts) You are given the code (including the main function) for evaluating an...

Q5 - 15 pts) You are given the code (including the main function) for evaluating an expression that is input in the postfix format. You will modify the code in the main function so that it can evaluate an expression that is input in the prefix format and print the intermediate results as well as the final result of the evaluation. You should also test your code with an expression string in prefix format that comprises of all the four operators (at least once) in a randomly chosen order with randomly chosen values in the range 10 to 50. For example, a sample expression string (prefix notation) could be input as -, +, *, /, 15, 12, 23, 44, 38 for the expression (infix notation) 15 / 12 * 23 + 44 - 38.

CODE in C++:

#include <iostream>

#include <string>

#include <cstring>

using namespace std;

class Node{

private:

int data;

Node* nextNodePtr;

Node* prevNodePtr;

public:

Node(){}

void setData(int d){

data = d;

}

int getData(){

return data;

}

void setNextNodePtr(Node* nodePtr){

nextNodePtr = nodePtr;

}

Node* getNextNodePtr(){

return nextNodePtr;

}

void setPrevNodePtr(Node* nodePtr){

prevNodePtr = nodePtr;

}

Node* getPrevNodePtr(){

return prevNodePtr;

}

};

class Stack{

private:

Node* headPtr;

Node* tailPtr;

public:

Stack(){

headPtr = new Node();

tailPtr = new Node();

headPtr->setNextNodePtr(0);

tailPtr->setPrevNodePtr(0);

}

Node* getHeadPtr(){

return headPtr;

}

Node* getTailPtr(){

return tailPtr;

}

bool isEmpty(){

if (headPtr->getNextNodePtr() == 0)

return true;

return false;

}

void push(int data){

Node* newNodePtr = new Node();

newNodePtr->setData(data);

newNodePtr->setNextNodePtr(0);

Node* lastNodePtr = tailPtr->getPrevNodePtr();

if (lastNodePtr == 0){

headPtr->setNextNodePtr(newNodePtr);

newNodePtr->setPrevNodePtr(0);

}

else{

lastNodePtr->setNextNodePtr(newNodePtr);

newNodePtr->setPrevNodePtr(lastNodePtr);

}

tailPtr->setPrevNodePtr(newNodePtr);

}

int pop(){

Node* lastNodePtr = tailPtr->getPrevNodePtr();

Node* prevNodePtr = 0;

int poppedData = -100000; //empty stack

if (lastNodePtr != 0){

prevNodePtr = lastNodePtr->getPrevNodePtr();

poppedData = lastNodePtr->getData();

}

else

return poppedData;

if (prevNodePtr != 0){

prevNodePtr->setNextNodePtr(0);

tailPtr->setPrevNodePtr(prevNodePtr);

}

else{

headPtr->setNextNodePtr(0);

tailPtr->setPrevNodePtr(0);

}

return poppedData;

}

int peek(){

Node* lastNodePtr = tailPtr->getPrevNodePtr();

if (lastNodePtr != 0)

return lastNodePtr->getData();

else

return -100000; // empty stack

}

};

int main(){

Stack stack;

string expression;

cout << "Enter the expression to evaluate: ";

getline(cin, expression);

char* expressionArray = new char[expression.length()+1];

strcpy(expressionArray, expression.c_str());

char* cptr = strtok(expressionArray, ", ");

while (cptr != 0){

string token(cptr);

bool isOperator = false;

if ( (token.compare("*") == 0) || (token.compare("/") == 0) || (token.compare("+") == 0) || (token.compare("-") == 0) )

isOperator = true;

if (!isOperator){

int val = stoi(token);

stack.push(val);

}

if (isOperator){

int rightOperand = stack.pop();

int leftOperand = stack.pop();

if (token.compare("*") == 0){

int result = leftOperand * rightOperand;

cout << "intermediate result: " << result << endl;

stack.push(result);

}

else if (token.compare("/") == 0){

int result = leftOperand / rightOperand;

cout << "intermediate result: " << result << endl;

stack.push(result);

}

else if (token.compare("+") == 0){

int result = leftOperand + rightOperand;

cout << "intermediate result: " << result << endl;

stack.push(result);

}

else if (token.compare("-") == 0){

int result = leftOperand - rightOperand;

cout << "intermediate result: " << result << endl;

stack.push(result);

}

}

cptr = strtok(NULL, ", ");

}

cout << "final result: " << stack.pop() << endl;

return 0;

}

Solutions

Expert Solution

#include <cstring>
#include<bits/stdc++.h>
using namespace std;

class Node
{
    private:
        int data;
        Node* nextNodePtr;
        Node* prevNodePtr;
    public:
        Node(){}
        void setData(int d)
        {
            data = d;
        }
        int getData()
        {
            return data;
        }
        void setNextNodePtr(Node* nodePtr)
        {
            nextNodePtr = nodePtr;
        }
        Node* getNextNodePtr()
        {
            return nextNodePtr;
        }
        void setPrevNodePtr(Node* nodePtr)
        {
            prevNodePtr = nodePtr;
        }
        Node* getPrevNodePtr()
        {
            return prevNodePtr;
        }

};

class Stack
{
    private:
        Node* headPtr;
        Node* tailPtr;
    public:
        Stack()
        {
            headPtr = new Node();
            tailPtr = new Node();
            headPtr->setNextNodePtr(0);
            tailPtr->setPrevNodePtr(0);
        }
        Node* getHeadPtr()
        {
            return headPtr;
        }
        Node* getTailPtr()
        {
            return tailPtr;
        }
        bool isEmpty()
        {
            if (headPtr->getNextNodePtr() == 0)
                return true;
            return false;
        }
        void push(int data)
        {
            Node* newNodePtr = new Node();
            newNodePtr->setData(data);
            newNodePtr->setNextNodePtr(0);
            Node* lastNodePtr = tailPtr->getPrevNodePtr();
            if (lastNodePtr == 0)
            {
                headPtr->setNextNodePtr(newNodePtr);
                newNodePtr->setPrevNodePtr(0);
            }
            else
            {
                lastNodePtr->setNextNodePtr(newNodePtr);
                newNodePtr->setPrevNodePtr(lastNodePtr);
            }
            tailPtr->setPrevNodePtr(newNodePtr);
        }
        int pop()
        {
            Node* lastNodePtr = tailPtr->getPrevNodePtr();
            Node* prevNodePtr = 0;
            int poppedData = -100000; //empty stack
            if (lastNodePtr != 0)
            {
                prevNodePtr = lastNodePtr->getPrevNodePtr();
                poppedData = lastNodePtr->getData();
            }
            else
                return poppedData;
            if (prevNodePtr != 0)
            {
                prevNodePtr->setNextNodePtr(0);
                tailPtr->setPrevNodePtr(prevNodePtr);
            }
            else
            {
                headPtr->setNextNodePtr(0);
                tailPtr->setPrevNodePtr(0);
            }
            return poppedData;
        }
        int peek()
        {
            Node* lastNodePtr = tailPtr->getPrevNodePtr();
            if (lastNodePtr != 0)
                return lastNodePtr->getData();
            else
                return -100000; // empty stack
        }
};

int main()
{
    int i;
    Stack stack1;
    string expression;
    cout << "Enter the expression to evaluate: ";
    getline(cin, expression);
    char* expressionArray = new char[expression.length()+1];
    strcpy(expressionArray, expression.c_str());
    char* cptr = strtok(expressionArray, ", ");
    vector<string> v;
    while(cptr!=NULL)
    {
        v.push_back(cptr);
       // cout<<cptr<<" ";
        cptr =strtok(NULL, ", ");
    }
    cout<<endl;
    stack <string> s;
  
    for(i=v.size()-1;i>=0;i--)
    {
        //cout<<v[i]<<" ";
        if((v[i]!="*")&&(v[i]!="/")&&(v[i]!="+")&&(v[i]!="-"))
        {
            v[i]+=",";
            s.push(v[i]);
        }
        else
        {
            string s3;
            string s1,s2;
            s1=s.top();
            s.pop();
            s2=s.top();
            s.pop();
            s3=s1+s2+v[i]+",";
            s.push(s3);
        }
    }
    //cout<<endl;
    string str=s.top();
    s.pop();
    strcpy(expressionArray, str.c_str());
    cptr = strtok(expressionArray, ", ");
    while (cptr != 0)
    {
        string token(cptr);
        bool isOperator = false;
        if ( (token.compare("*") == 0) || (token.compare("/") == 0) || (token.compare("+") == 0) || (token.compare("-") == 0) )
            isOperator = true;
        if (!isOperator)
        {
            int val = stoi(token);
            stack1.push(val);
        }
        if (isOperator)
        {
            int rightOperand = stack1.pop();
            int leftOperand = stack1.pop();
            if (token.compare("*") == 0)
            {
                int result = leftOperand * rightOperand;
                cout << "intermediate result: " << result << endl;
                stack1.push(result);
            }
            else if (token.compare("/") == 0)
            {
                int result = leftOperand / rightOperand;
                cout << "intermediate result: " << result << endl;
                stack1.push(result);
            }
            else if (token.compare("+") == 0)
            {
                int result = leftOperand + rightOperand;
                cout << "intermediate result: " << result << endl;
                stack1.push(result);
            }
            else if (token.compare("-") == 0)
            {
                int result = leftOperand - rightOperand;
                cout << "intermediate result: " << result << endl;
                stack1.push(result);
            }
        }
        cptr = strtok(NULL, ", ");
    }
    cout << "final result: " << stack1.pop() << endl;
    return 0;
}


Related Solutions

Q5 [15 pts] a) Convert the following NFA to a DFA: 0 1 ---------------------- -> a...
Q5 [15 pts] a) Convert the following NFA to a DFA: 0 1 ---------------------- -> a || {a} | {a,b} b || {c} | {c} c || {d} | {d} d || {e} | {e} * e || {} | {} b) Informally describe the language that it accepts.
Split the main function given into multiple functions. You have been given a very simple program...
Split the main function given into multiple functions. You have been given a very simple program that performs basic operations (addition, subtraction, editing) on two randomly generated integer vectors. All functionality has been included in main, causing code segments to be repeated as well as diminishing the readability. Rewrite the program by grouping calculations and related operations into functions. In particular, your program should include the following functions. InitializeVectors: This is a void function that initializes the two vectors by...
Create all necessary code to make this main function work. It is not allowed to change...
Create all necessary code to make this main function work. It is not allowed to change the main function. int main() {        int ListDataSample1[] = { 1, 1, 1 };        int ListDataSample2[] = { 2, 2, 2 };        List<int> List1 = List<int>(ListDataSample2, 3);        List<int> List2 = List<int>(ListDataSample2, 3);               cout << "List1 :" << List1 << endl;        cout << "List2 :" << List2 << endl << endl;        List1 += List2;               cout...
Translate the following C code to MIPS assembly. The main function and subfunction are translated to...
Translate the following C code to MIPS assembly. The main function and subfunction are translated to two separate .asm files. Finish the assembly code segment for the above requirement. int main() { int x=2; int y=1; int z=0; z=Subfunc(x,y); printf(“Value of z is: %d”, z); } int Subfunc(int x, int y) { int t1=0; t1=x+y+100; return t1;} File 1: .data str: .asciiz "The value of z:" .text #.globl main main: addi $s0, $0,2 #x addi $s1, $0,1 #y addi $s2,...
How do I go back to the start of the main method with the given code?...
How do I go back to the start of the main method with the given code? Hello I am making this java program and there is a point in the code where if the user types the character y it will start the program back at the beginning of the main method. How can I do this without drastically changing the code? For instance, if I type y, the program will go back to line 1 and repeat the entire...
Add two lines of code in main() function to create a variable, goodStudent, whose type is...
Add two lines of code in main() function to create a variable, goodStudent, whose type is Student with name, "John" and age, 21. public class Student { private String name; private int age; public Student(){ name = ""; age= 0; } public Student(String initName){ name = initName; age = 0; } public String getName() { return name; } public void setAge(int anAge) { age = anAge; } public static void main (String[] args) { // !!!! Your two lines of...
Q2 - 15 pts) Given a minimum unimodal array of integers, run the binary search algorithm...
Q2 - 15 pts) Given a minimum unimodal array of integers, run the binary search algorithm to find the minimum element. You need to show the initial and the iteration-level values of the left index, right index and middle index as well as your decisions to reduce the search space in each iteration. 0 1 2 3 4 5 6 7 8 9 33 32 27 26 24 22 21 8 7 3 IN C++ PLEASE
Given: CO2 A. What is the main function of this molecule as discussed this semester? B....
Given: CO2 A. What is the main function of this molecule as discussed this semester? B. biofuel molecule GHG responsible for climate change and global warming c. food molecule D. reacttant in fermentation
Write code in your “main” function that performs the following: a) For each n є {10^3,...
Write code in your “main” function that performs the following: a) For each n є {10^3, 5x10^3, 10^4, 5x10^4, 10^5}, randomly generate 5 integer arrays of length n. b) Run each of the five comparison sorts you implemented in Step 1 on all the five arrays generated in Step 2.a and record the worst-case actual running time and number of comparisons performed among elements in the input array. #include<iostream> #include<cmath> using namespace std; void displayArray(int a[], int n) { cout<<"\nArray...
Problem 1. (20 Pts) Two storage structures, given code names Y and Z, are being considered...
Problem 1. (20 Pts) Two storage structures, given code names Y and Z, are being considered for a military base. The military uses a 6% percent/year expected rate of return and a 24-year life for decisions of this type. The relevant characteristics for each structure are shown below. Structure Y Structure Z First Cost 24225 24225 Estimated Life 12 years 24 years Estimated Salvage Value None $1,800 Annual Maintenance Cost $1,000 $720 a) What is the future worth of each...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT