Wednesday, January 31, 2024

Evaluation of PostFix Expression - DSTC using C Language (Source Code Implemented)


EVALUATE POSTFIX Expression
Implemented using C Language

C Language Code:  


EVALPOST.C

 //   DSTC  --- EVALPOST.C  ..... evaluation of POSTFIX expres..
// using the Stacks ... in linked list s

#include "stack.h"
#include <conio.h>
#define TRUE 1
#define FALSE 0
int isOperand(char a)
{
    if(a>='0' && a<='9')
        return TRUE;
    else
        return FALSE;
}

int eval(int b, int a, char op)
{
    // printf("testing: %d %d %c\n", a, b, op);
    switch(op)
    {
    case '+':
        return a+b;
    case '-':
        return a-b;
    case '*':
        return a*b;
    case '/':
        return a/b;
    }
    return 0;
}

void main()
{
    char in[80];
    int i,c;

    Stack *s;
    s=GetStack();
    clrscr();

    printf("Enter postfix expression: ");
    gets(in);

    for(i=0;in[i]!='\0';i++)
    {
        if(isOperand(in[i]))
            push(s,in[i]-'0');
        else
        {
            c=eval(pop(s), pop(s), in[i]);
            push(s,c);
        }
    }
    printf("Result is: %d", pop(s));
}
 


STACK.H

 // DSTC ---- STACK.H .....
// stacks using LINKED LIST ...

#include <stdio.h>
#include <stdlib.h>
typedef struct nd
{
    int info;
    struct nd *next;
}Node;

typedef struct {
    Node *top;
}Stack;

Stack * GetStack()
{
    Stack *temp;
    temp=(Stack *)malloc(sizeof(Stack));
    temp->top=NULL;
    return temp;
}

Node * GetNode()
{
    Node *n;
    n=(Node *)malloc(sizeof(Node));
    return n;
}

int empty(Stack *s)
{
    if(s->top==NULL)
        return 1;
    else
        return 0;
}

void push(Stack *s, int i)
{
    Node *n;
    n=GetNode();
    n->info=i;
    n->next=s->top;
    s->top=n;
}

int pop(Stack *s)
{
    int i;
    Node *t;
    if(s->top==NULL)
    {
        printf("Stack underflow\n");
        return NULL;
    }
    i=s->top->info;
    t=s->top;
    s->top=t->next;
    free(t);
    return i;
}

No comments: