Sunday, 31 July 2016

Evaluate Postfix


stack.h


#include <stdlib.h>
typedef struct stack
{
    int *values;
    int maxSize;
    int top;
}stack;

stack * createstack(int maxElements)
{
    //create stack
    stack *s;
    s = (stack *)malloc(sizeof(stack));
    
    //initialize
    s->values = (int *)malloc(sizeof(int)*maxElements);
    s->top = -1;
    s->maxSize = maxElements;
    
    //return
    return s;
}

void init(stack *s,int maxElements)
{
    s = (stack *)malloc(sizeof(stack));
    
    //initialize
    s->values = (int *)malloc(sizeof(int)*maxElements);
    s->top = -1;
    s->maxSize = maxElements;
}

void push(stack *s, int n)
{
    if(s->top == s->maxSize)
    {
        printf("stack is Full\n");
    }
    else
    {
        printf("Pushing Value:%d\n",n);

        //increament first then push
        ++s->top;
        s->values[s->top] = n;
    }
    return;
}

int pop(stack *s)
{
    int value;
    if(s->top == -1)
    {
        printf("stack is Empty\n");
    }
    else
    {
        //remove first then decrement
        value = s->values[s->top];
        s->top--;
        printf("Poping value:%d\n",value);
    }
    return  value;
}

void display(stack *s)
{
    int i=0;
    for(i=0;i<=s->top;i++)
    {
        printf("%d ",s->values[i]);
    }
}

imp.c


#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include "stack.h"
int calc(int n1,int n2, char c){
  switch(c)
  {
    case '*':
      return n1*n2;
      break;

    case '/':
      return n1/n2;
      break;

    case '+':
      return n1+n2;
      break;

    case '-':
      return n1-n2;
      break;

    default:
      return 0;
  }
}

void main()
{
  int i=0,value=0;
  stack *s = createstack(10);
  char *exp = "10 10 10 9 * + +";
  for(i=0;i<strlen(exp);i++)
  {
    if(isdigit(exp[i]))
    {
      value = (value * 10) + (exp[i] - '0');
    }
    else if(exp[i] == '+' || exp[i] == '*' || exp[i] == '/' || exp[i] == '-'){
      value = calc(pop(s),pop(s),exp[i]);
    }
    else
    {
      push(s,value);
      value =0;
    }
  }
  printf("%d\n",value);
}

http://bebe.com

0 comments:

Post a Comment