Question

In: Computer Science

This code needs to run a working Reverse Polish Calculator, but when I input my commands...

This code needs to run a working Reverse Polish Calculator, but when I input my commands it only pops my inputs never push them. So my answer is always zero.

Here is my code.

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

struct Node
{
int element;
struct Node *next;
};

//Global variable
struct Node *top = NULL;

void push(int ele)
{
struct Node *newNode;

newNode = (struct Node *) malloc(sizeof(struct Node));

newNode->element = ele;
newNode->next = top;
top = newNode;
}

void pop()
{
struct Node *temp;
temp = top;

if(top == NULL)
printf("Stack is empty!!!\n");
else
{
top = top->next;
printf("%d is popped from the stack\n", temp->element);
free(temp);
}


}

bool isEmpty()
{
if(top == NULL)
return true;
else
return false;
}

int returnTopElement()
{
return top->element;
}

void printStack()
{
struct Node *temp;
temp = top;

printf("Stack : ");

while(temp != NULL)
{
printf("%d ", temp->element);
temp = temp->next;
}

printf("\n");
}

int oneByOne(){
char test; //taking character input
int num = 0;
int num1;
int num2;
int atleastone = 0;
printf("Enter your inputs separated by a space and the operation.\n");
printf("Enter ! when you are done.\n");

while(1){
scanf("%c",&test); //take input of current character
printf("%c is user character\n", test);
if(test == '!'){break;} //terminates character
if(test == ' ' || test == '\n'){ //allows for space or newline input
if(atleastone) //check if at least one previous digit scanned
push(num);
num = 0, atleastone = 0;
continue;
}
else if(test>='0' && test <='9'){
atleastone = 1;
num = num*10 + (test - '0');
continue;
}
if(top == NULL){
printf("This operation is invalid.\n");
break;
}
num1 = returnTopElement(); pop();
if(top == NULL){
printf("This operation is invalid.\n");
break;
}
num2 = returnTopElement(); pop();
if(test == '+');
push(num2+num1); //allows addition
if(test == '-');
push(num2-num1); //allows subtraction
if(test == '*');
push(num2*num1); //allows multiplication
if(test == '/');
push(num2/num1); //allows division
}
if(top == NULL)
return -1;
return returnTopElement();
}

int arrayInput(char** inputArray){
int i = 0;
int atleastone = 0;
int num = 0;
int num1;
int num2;
char test;
while((*inputArray)[i] != '\0'){
test = (*inputArray)[i];i++; //gets char input from function
if(test == '!'){break;} //terminate character
if(test == ' ' || test == '\n'){ //allows for space or newline input
if(atleastone)
push(num);
num = 0, atleastone = 0;
continue;
}
else if(test >= '0' && test <= '9'){
atleastone = 1;
num = num*10 + (test- '0');
continue;
}
if(top == NULL){
printf("This operation is invalid.\n");
break;
}
num2 = returnTopElement(); pop();
if(test == '+');
push(num2+num1); //allows addition
if(test == '-');
push(num2-num1); //allows subtraction
if(test == '*');
push(num2*num1); //allows multiplication
if(test == '/');
push(num2/num1); //allows division
}
if(top == NULL)
return -1;
return returnTopElement();
}

int main(int argc, const char * argv[]) {

printf("Check oneByone function: \n");
int ans = oneByOne();
if(top == NULL){
printf("The input is invalid.\n");
}
else{
printf("The answer is %d\n", ans);
}

char * e = "23 45 + 3 *";
char ** expression = &e;
printf("\nChecking arrayInput function for %s \n", *expression);
printf("The above expression is hardcoded in the code itself. \n");
ans = arrayInput(expression);
if(top == NULL){
printf("The input expression is invalid. \n");
}
else{
printf("The answer of the input expression is %d\n", ans);
}

return 0;
}

Solutions

Expert Solution

class Solution {
public:
int evalRPN(vector &tokens) {
stack<int> nums;
int len = tokens.size();
for (int i = 0; i < len; i ++) {   
string x = tokens[i];   
if ((x == "+") || (x == "-") || (x == "*") || (x == "/")) {   
// pop two numbers off the stack   
int a = nums.top();   
nums.pop();   
int b = nums.top();   
nums.pop();   
// evaluate and push the result back   
switch (x[0]) {   
case '+': nums.push(a + b); break;   
case '-': nums.push(b - a); break;   
case '*': nums.push(b * a); break;   
case '/': nums.push(b / a); break;   
}   
} else { // push a number into the stack   
int n;   
istringstream(x) >> n;
nums.push(n);
}
}
if (nums.size()) {
int xx = nums.top();
while (nums.size()) {
nums.pop();
}
return xx;
}
return 0; // error occurs
}
};

try this


Related Solutions

Below is my source code for file merging. when i run the code my merged file...
Below is my source code for file merging. when i run the code my merged file is blank and it never shows merging complete prompt. i dont see any errors or why my code would be causing this. i saved both files with male names and female names in the same location my source code is in as a rtf #include #include #include using namespace std; int main() { ifstream inFile1; ifstream inFile2; ofstream outFile1; int mClientNumber, fClientNumber; string mClientName;...
Here is my fibonacci code using pthreads. When I run the code, I am asked for...
Here is my fibonacci code using pthreads. When I run the code, I am asked for a number; however, when I enter in a number, I get my error message of "invalid character." ALSO, if I enter "55" as a number, my code automatically terminates to 0. I copied my code below. PLEASE HELP WITH THE ERROR!!! #include #include #include #include #include int shared_data[10000]; void *fibonacci_thread(void* params); void parent(int* numbers); int main() {    int numbers = 0; //user input....
Reverse Polish (HP) Style Calculator - Part 2 The purpose of this assignment is to incorporate...
Reverse Polish (HP) Style Calculator - Part 2 The purpose of this assignment is to incorporate an abstract class and inheritance and add it to the interface of the business calculator created in Topic 4. • Implement a pure abstract stack class named AbstractStack that has no implementation. It will not have a private array of double, because that is an implementation detail of ArrayStack that would not be found in other implementations such as LinkedStack. Nor will it have...
REVERSE POLISH CALCULATOR C++ ONLY. For this assignment, you are to write a program, which will...
REVERSE POLISH CALCULATOR C++ ONLY. For this assignment, you are to write a program, which will calculate the results of Reverse Polish expressions that are provided by the user. You must use a linked list to maintain the stack for this program (NO array implementations of the stack). You must handle the following situations (errors): Too many operators (+ - / *) Too many operands (doubles) Division by zero The program will take in a Polish expression that separates the...
How would I make it so that when I run my code it does not ask...
How would I make it so that when I run my code it does not ask for input (not having to enter after the statement and enter 0 for example) after ROXY (Forever ROXY Enterprises) appears? Like it would tell me the second statement right away along with the Roxy phrase. This is in C++. My code: #include / #include using std::endl; int main() {    void readAndConvert();    unsigned int stockSymbol;    unsigned int confNum;    std::cout << "ROXY...
Write a Reverse Polish Calculator, RPN We discussed in class a general implementation of RPN using...
Write a Reverse Polish Calculator, RPN We discussed in class a general implementation of RPN using a stack to keep track of the numbers. Each time an operand is encountered, two values are popped from this stack, the given operation is performed, and the result is pushed back onto the stack. Utilize Java generic Stack Class to implement this algorithm with four arithmetic operations: +, *, -, /. It is suggested that you implement a class RPN with a single...
Write a Reverse Polish Calculator, RPN in JAVA Each time an operand is encountered, two values...
Write a Reverse Polish Calculator, RPN in JAVA Each time an operand is encountered, two values are popped from this stack, the given operation is performed, and the result is pushed back onto the stack. Utilize Java generic Stack Class to implement this algorithm with four arithmetic operations: +, *, -, /. Implement a class RPN with a single static method evaluate. This method should have the following signature:             public static String evaluate(String expression) It should split the passed...
My Javascript code isn't working (when i press calculate button) - what's wrong with it ?...
My Javascript code isn't working (when i press calculate button) - what's wrong with it ? Car Rental Enter Number of Rental Days: Select Car Type: onclick= "priceofcar = 50;"/> Compact onclick= "priceofcar = 60;"/> Economy onclick= "priceofcar = 70;"/> Intermediate Select Loss Damage Waiver onclick= "damagewaiver='yes'"/> Yes onclick= "damagewaiver='no'"/> No damagewaiver = boxDays.value * 25;} else if (damagewaiver == No) { damagewaiver = 0; }/> Select Roadside Issues Coverage: onclick= "issuescoverage='yes'"/> Yes onclick= "issuescoverage='no'"/> No issuescoverage = boxDays.value *...
Hey, I have a code that I am working on to make a garden plot calculator,...
Hey, I have a code that I am working on to make a garden plot calculator, however I am reaching an error that I cannot seem to get past. Please help. import math # GarednPlot contains all the utility functions class GardenPlot: # constructor function: Welcomes the user and sets default values def __init__(self): print("Welcome!") self.length = 0 self.radius = 0 self.depth = 0 # Sets the length of the GardenPlot and returns that length def setLength(self): self.length = float(input("Enter...
Let's try to develop a C++ Reverse Polish Notation (RPN) calculator! Create a base class called...
Let's try to develop a C++ Reverse Polish Notation (RPN) calculator! Create a base class called Operand Give it a virtual destructor to avoid any weird problems later on! Derive a class called Number from Operand Maintain a double member variable in class Number For simplicity, you may make the member variable public if you would like Derive a class called Operator from Operand Derive a class called Add from Operator (2 + 3 = 5) Derive a class called...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT