Answer the question
In order to leave comments, you need to log in
Polish entry. Where is the mistake?
The expression a*b/(a+b) is given. Organize the calculation of this expression using the Polish notation algorithm. Apply system stack.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "stack.h"
int main ()
{
P_STACK st;
P_NODE nd;
char expr = "*+ab-cd";
char ch;
int a, b, c, d, i, aStep, bStep, cStep, dStep, add, mult, sub, res;
st = (P_NODE) malloc (sizeof (stack));
init_stack (st);
i = 0;
while (expr[i]!='\0')
{
nd=(P_NODE) malloc (sizeof (node));
nd->info=expr[i];
push (st, nd);
i++;
}
printf ("Enter the 4th number:");
scanf ("%d%d%d%d", &a, &b, &c, &d);
while (!is_stack_empty (st))
{
nd = pop (st);
if (!is_stack_empty (st))
switch (nd->info)
{
case 'd':
dStep=d;
break;
case 'c':
cStep=c;
break;
case '-':
sub=cStep-dStep;
break;
case 'b':
bStep=b;
break;
case 'a':
aStep=a;
break;
case '+':
add=bStep+aStep;
break;
case '*':
mult=add*sub;
break;
}
}
res=mult;
printf ("Result: [expr=%d] = [%d]", expr, res);
return 0;
}
#ifndef STACK_H_
#define STACK_H_
typedef struct NODE NODE;
typedef struct NODE *P_NODE;
typedef struct STACK STACK;
typedef struct STACK *P_STACK;
struct NODE
{
int info;
P_NODE next;
} node;
struct STACK
{
int count;
int size;
P_NODE top;
} stack;
typedef enum {false, true} bool;
void init_stack (P_STACK st);
bool is_stack_empty (P_STACK st);
void push (P_STACK st, P_NODE nd);
P_NODE pop (P_STACK st);
void print_stack (P_STACK st);
#endif
Answer the question
In order to leave comments, you need to log in
You have a different expression in your code: (a + b) * (c - d)
Where is the stack implementation?
By implementation:
1. For calculations, you do not need 4 variables or 10 (depending on how many are in the expression), two are enough for ordinary binary operations (with two operands). The result of the intermediate calculation must be again inserted onto the stack in place of the pulled out operands and operation.
2. The calculation algorithm for direct Polish notation is well described on the wiki.
Thus, the stack is not very suitable here, in addition to the push and pop operations, you also need to traverse the list in the forward direction and insert / remove elements at an arbitrary position.
Or as an option with a stack - use 2 stacks. That is, you extract the pending ones from one and place the results of the calculations in the second until the first is empty, then switch to the second and so on until the only value remains on the stack - the result of the calculations.
Either with one stack, but change the implementation. So that there is no P_STACK structure.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question