02 December 2010

Stack infix in C

Based on the post of "Stack implementation in C", here's Stack infix implementation in C:

// the idea of this example from "Data Structures and Algorithms using C#"
// main_stack_infix.c

#include <stdio.h>
#include <ctype.h>
#include "stack.h"

#define CHAR_TO_INT(x) ((x)-48)

void calc(struct stack*, struct stack*);

int main(void)
{
struct stack s1, s2;
char *equation = "1 + 2 - 9 ";
int count=0;

init(&s1);
init(&s2);

while (*equation != '\0')
{
if (count == 2)
{
calc(&s1, &s2);
count=1;
}

if (isdigit(*equation) != 0)
{
push(&s1, CHAR_TO_INT(*equation));
count++;
}else if (ispunct(*equation) != 0)
{
push(&s2, *equation);
}
equation++;
}
printf("%i\n", peek(&s1));
return 0;
}

void calc(struct stack *s1, struct stack *s2)
{
int x = pop(s1);
int y = pop(s1);
int op = pop(s2);
int ret = 0;

switch (op)
{
case '+':
ret = y+x;
break;
case '-':
ret = y-x;
break;
case '*':
ret = y*x;
break;
case '/':
ret = y/x;
break;
}

push(s1, ret);
}

No comments: