Our infix system 1 + 2 - 1 is represented in post fix notation as 1 2 + 1 -
http://en.wikipedia.org/wiki/Reverse_Polish_notation
The infix to post fix algorithm:
http://en.wikipedia.org/wiki/Shunting_yard_algorithm
Code Snippet:
#include "parser.h"
#define INITIAL_STACK_SIZE 5
void operate (init_data_t *, Stack *);
int main (int argc, char **argv)
{
init_data_t *data;
Stack *stack;
data = init (stdin);
stack = stack_init (INITIAL_STACK_SIZE);
operate (data, stack);
return 0;
}
void operate (init_data_t *data, Stack *stack)
{
int op1, op2, i = 0;
char *result = NULL;
while (i <>numlines)
{
print_semicolon_expr (data->lines[i]);
result = strtok (data->lines[i], ",");
while (result != NULL)
{
if (atoi (result) != 0)
stack_push (stack, atoi (result));
else
{
switch (result[0])
{
case '+':
op2 = stack_pop (stack);
op1 = stack_pop (stack);
stack_push (stack, (op1 + op2));
break;
case '*':
op2 = stack_pop (stack);
op1 = stack_pop (stack);
No comments:
Post a Comment