Infix to postfix

 

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAX 100

char stack[MAX];
char infix[MAX],postfix[MAX];
int top = -1;

int precedence(char symbol){
    switch (symbol)
    {
    case '^':
        return 3;
    case '/':
    case '*':
        return 2;
    case '+':
    case '-':
        return 1;
    default:
        return 0;
    }
}

char pop(){
    char c;
    if(top==-1){
        printf("Stack Underflow\n");
        exit(1);
    }
    c = stack[top];
    top--;
    return c;
}

void push(char c){
    if(top==MAX-1){
        printf("Stack Overflow\n");
        return;
    }
    top++;
    stack[top] = c;
}

int space(char c){
    if(c==' '|| c=='\t')
        return 1;
    else
        return 0;
}

int isEmpty(){
    if(top==-1){
        return 1;
    }
    else{
        return 0;
    }
}

void print(){
    int i=0;
    printf("Postfix expression: ");
    while(postfix[i]){
        printf("%c",postfix[i++]);
    }
    printf("\n");
}

void toPostfix(){
    int len = strlen(infix);
    int i,j=0;
    char symbol,next;
    for(i=0;i<len;i++){
        symbol = infix[i];
        if(!space(symbol)){
            switch (symbol)
            {
            case '(':
                push(symbol);
                break;
            case ')':
                while((next=pop()) != '('){
                    postfix[j++] = next;
                }
                break;
            case '+':
            case '-':
            case '*':
            case '/':
            case '^':
                while(!isEmpty() && precedence(stack[top])>=precedence(symbol)){
                    postfix[j++] = pop();
                }
                push(symbol);
                break;
            default:
                postfix[j++] = symbol;
                break;
            }
        }
    }
    while (!isEmpty())
    {
        postfix[j++] = pop();
    }
    postfix[j] = '\0';
}

int main(){
    printf("Enter the Infix expression: ");
    gets(infix);

    toPostfix();
    print();
    return 0;
}

Comments