Question

(Using C++) Create a function that will solve integer postfix equations. (must implement own stack, can’t...

(Using C++) Create a function that will solve integer postfix equations. (must implement own stack, can’t use std::stack )
0 0
Add a comment Improve this question Transcribed image text
Answer #1

#include <iostream>
#include <stdio.h>

#include <string.h>

char stack[100];   
int top = -1;

void printArray(int array[], int size) {
int i;
for ( i = 0; i < size; i++)
{
printf("%d,", array[i]);
}
printf("\n");
}

int isempty() {

if(top == -1)
return 1;
else
return 0;
}
  
int isfull() {

if(top == 99)
return 1;
else
return 0;
}

int peek() {
return stack[top];
}


int pop() {
int data;

if(!isempty()) {
data = stack[top];
top = top - 1;  
return data;
}else {
printf("Could not retrieve data, Stack is empty.\n");
}
}

int push(int data) {

if(!isfull()) {
top = top + 1;  
printf("push %d, top is %d\n", data, top);
stack[top] = data;
//printf("push stack[top] = data, top is %d\n", top);
}else {
printf("Could not insert data, Stack is full, top is %d.\n", top);
}
}
int eval(int op1, int op2, char operate) {
switch (operate) {
case '*': return op2 * op1;
case '/': return op2 / op1;
case '+': return op2 + op1;
case '-': return op2 - op1;
default : return 0;
}
}
int processexpr(char expr[])
{
// write this function
int i = 0;
char ch;
int val;
int size = strlen(expr);
while (expr[i]!='\0') {
ch = expr[i];
if(ch=='=')
return val;
if (isdigit(ch)) {
push(ch-'0');
}
else {
int op1 = peek();
pop();
int op2 = peek();
pop();
val = eval(op1, op2, ch);
push(val);
}
i++;
}
return val;

}

int main() {

char expr[100] = "31+=";
int x = processexpr(expr);
printf("%s %d\n", expr, x);

// make your own postfix expression to test
// and print out the result
}
===================================
See Output

saved share run gcc version 4.6.3 push 3, top is 0 push 1, top is1 push 4, top is 0 31+- 4 main.cpp 67 68 69 70 case -: ret
Thanks

Add a comment
Know the answer?
Add Answer to:
(Using C++) Create a function that will solve integer postfix equations. (must implement own stack, can’t...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT