Conversion of Infix to postfix using STACK

amannarayanm · updated October 14, 2021 · C
#include<stdio.h>
#include<stdlib.h>
#include<string.h>

struct stack {
  int top;
  int size;
  char *arr;
};

int isFull(struct stack *ptr){
    if(ptr->top == ptr->size-1){
        return 1;
    }
    return 0;
}

int isEmpty(struct stack *ptr){
    if(ptr->top == -1){
        return 1;
    }
    return 0;
}


void push(struct stack *ptr,char ch){
    if(isFull(ptr)){
        printf("\nStack OverFlow!");
    }
    else{
        ptr->top++;
        ptr->arr[ptr->top] =  ch;
    }
}

char pop(struct stack *ptr){
    if(isEmpty(ptr)){
        printf("\nStack UnderFlow!");
    }
    else{
        char ch1 = ptr->arr[ptr->top];
        ptr->top--;
        return ch1;
    }
}

char peek(struct stack *ptr,int posi){
    int newIndex = ptr->top-posi+1;
    if(newIndex<0){
        return -1;
    }
    else{
        return ptr->arr[newIndex];
    }
}

int isOperator(char ch){
    if(ch == '*' || ch == '/' || ch == '+' || ch == '-'){
        return 1;
    }
    return 0;
}

int precendence(char ch){
    if(ch == '*' || ch == '/'){
        return 3;
    }
    else if(ch == '+' || ch == '-'){
        return 2;
    }
    return 0;
}

char stackTop(struct stack *sp){
    return sp->arr[sp->top];
}

char* InfixToPostfix(char *infix){
    // creation of stack for storing the operator
    struct stack *sp = (struct stack*)malloc(sizeof(struct stack));
    sp->top = -1;
    sp->size = 10;
    sp->arr = (char *)malloc(sp->size*sizeof(char));
    
    char *postfix = (char *)malloc((strlen(infix)+1)*sizeof(char));
    
    int i= 0;   // for scanning the given string
    int j= 0;   // for storing the posfix element;
    
    while(infix[i] != '\0'){
        
        if(!isOperator(infix[i])){
            postfix[j] = infix[i];
            j++;
            i++;
        }
        else{
            if( precendence(infix[i]) > precendence(stackTop(sp)) ){
                push(sp,infix[i]);
                i++;
            }
            else{
                postfix[j] = pop(sp);
                j++;
            }
        }
    }
    while(!isEmpty(sp)){
        postfix[j] = pop(sp);
        j++;
    }
    postfix[j] = '\0';
    return postfix;
}

int main(){
    
    char myExpression[] = "x-y/z-k*d";
    
    printf("\nPrefix : %s",myExpression);
    printf("\nPostfix : %s",InfixToPostfix(myExpression));
    
    return 0;
}

Comments

amannarayanm October 14, 2021

This is my first longest Code

Please sign up or log in to contribute to the discussion.