Showing posts with label source code of INFIX INTO POSTFIX Expression. Show all posts
Showing posts with label source code of INFIX INTO POSTFIX Expression. Show all posts

Wednesday, January 31, 2024

INFIX INTO POSTFIX Expression - DSTC using C Language (Source Code Implemented)

INFIX INTO POSTFIX Expression
Implemented using C Language

C Language Code:


INTOPOST.C
 //   DSTC  --- INTOPOST.C  .....

// 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 prec(char op)
{
    switch(op) {
case '$':
    return 3;
case '*': case '/':case '%':
    return 2;
case '+': case '-':
    return 1;
    };
    return 0;
}

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

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

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

    for(i=0,k=0;in[i]!='\0';i++)
    {
        if(isOperand(in[i]))
            post[k++]=in[i];
        else
        {
            if(empty(s) || in[i]=='(')
                //if intially stack is empty
                //or current operator is '('
                //then push current operator
                push(s,in[i]);
            else if(in[i]==')')
            {
                //pop all the operators till '('
                //is encountered
                while((c=pop(s))!='(')
                    post[k++]=c;
            }
else if(prec(in[i]) < prec(s->top->info))
            {
                //if precedence of current operator is
                //less than or equal to the operator at the
                //top of the stack, then pop all
                //higher or equal precedence operators
                while(prec(in[i]) <= prec(s->top->info) && !empty(s))
                    post[k++]=pop(s);
                push(s,in[i]);
            }
            else
                push(s,in[i]);
        }
    }
    //pop all the remaining operators

     while(!empty(s))
        post[k++]=pop(s);

     post[k++]='\0';
    printf("The postfix expression is: %s", post);
}


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;
}