Write a program that evaluates postfix expression using array implementation of stack.
The expression [the input] is evaluated from left to right using a stack.
- When the element read from the expression is an operand, push it into the stack.
- When the element read from the expression is an operator:
- Pop two operands from the stack.
- Evaluate the two operands
- Push the result of the evaluation into the stack.
The final result lies on the top of the stack at the end of the calculation. Make sure to display the result before terminating the program.Write a program that evaluates postfix expression using array implementation of stack.
I've tried to combine some programs I had in my notes and such but I still have no idea what I'm doing wrong and how to fix this. I hope you guys help me out and if it's not too much explain why I'm wrong and how to fix it
Code:
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#define M 20
typedef struct{
char *stk[M];
int top;
int maxsize;
}STAK;
void inputString(char *);
void determOper(char *);
void push(STAK *,char);
char pop(STAK *);
void createStack(STAK *);
bool isFull(int);
bool isEmpty(int);
int main(void)
{
char str[M];
inputString(str);
determOper(str);
return 0;
}
void inputString(char *str[])
{
printf("Enter your expression: ");
gets(str);
return;
}
void creatStack(STAK *ostk)
{
char *newstk[M];
char newstk = malloc(sizeof(char)*M);
if(newstk==NULL)
printf("Error in allocation");
else
ostk->stk =newstk;
ostk->top = -1;
ostk -> maxsize = M;
}
void evalOperand(char stk[])
{
int op1,op2,i,tnum,result;
bool full,empty;
STAK ostk;
createStack(&ostk);
fgets(stk, M, stdin);
for (i = 0; i < strlen(stk); i++)
{
if (isdigit(stk[i]))
{
data = (data == -1) ? 0 : data;
data = (data * 10) + (stk[i] - 48);
continue;
}
if (data != -1)
{
push(data);
}
if (stk[i] == '+' || stk[i] == '-' || stk[i] == '*' || stk[i] == '/')
{
op2 = pop();
op1 = pop();
if (op1 == -1 || op2 == -1)
break;
switch (stk[i])
{
case '+':
result = op1 + op2;
push(result);
break;
case '-':
result = op1 - op2;
push(result);
break;
case '*':
result = op1 * op2;
push(result);
break;
case '/':
result = op1 / op2;
push(result);
break;
}
}
data = -1;
}
full = isFull(ostk);
if(full)
{
printf("Error: stack is full");
getch();
exit(1);
}
else
push(&ostk,result);
i = -1;
do{
empty = isEmpty(ostk.top);
if(!empty)
{
ret=pop(&ostk);
++i;
bin[i]=ret;
}
}while(!empty);
dispRes(result);
return;
}
bool isFull(STAK ostk)
{
return(ostk.top==(ostk.maxsize-1));
}
void push(STAK *ostk,char stk)
{
ostk->stk[++ostk->top] = stk;
return;
}
int pop(STAK *ostk)
{
int r;
r = ostk->stk[ostk->top--];
return r;
}
void dispBin(char stk[], int result)
{
printf("%d", result);
getch();
return;
}