InfixToPostfix

 avatar
unknown
plain_text
10 months ago
2.3 kB
199
Indexable
#include <stdio.h>
#include <ctype.h>  // for isalpha
#include <string.h> // for strlen

#define MAX 100

char stack[MAX];
int top = -1;

// Stack operations
void push(char ch)
{
    if (top < MAX - 1)
        stack[++top] = ch;
}

char pop()
{
    if (top >= 0)
        return stack[top--];
    return '\0';
}

char peek()
{
    if (top >= 0)
        return stack[top];
    return '\0';
}

// Function to return precedence of operators
int precedence(char op)
{
    switch (op)
    {
    case '^':
        return 3;
    case '*':
    case '/':
        return 2;
    case '+':
    case '-':
        return 1;
    default:
        return 0;
    }
}

// Check if operator is left associative (except ^)
int isLeftAssociative(char op)
{
    return (op != '^');
}

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

// Main function to convert infix to postfix
void infixToPostfix(char infix[], char postfix[])
{
    int i, j = 0;
    char ch;

    for (i = 0; infix[i] != '\0'; i++)
    {
        ch = infix[i];

        if (isalpha(ch))
        {
            // Operand: add to output
            postfix[j++] = ch;
        }
        else if (ch == '(')
        {
            push(ch);
        }
        else if (ch == ')')
        {
            while (top != -1 && peek() != '(')
                postfix[j++] = pop();
            pop(); // remove '('
        }
        else if (isOperator(ch))
        {
            while (top != -1 && isOperator(peek()) &&
                   (precedence(peek()) > precedence(ch) ||
                    (precedence(peek()) == precedence(ch) && isLeftAssociative(ch))))
            {
                postfix[j++] = pop();
            }
            push(ch);
        }
    }

    // Pop remaining operators
    while (top != -1)
    {
        postfix[j++] = pop();
    }

    postfix[j] = '\0'; // null terminate the string
}

// Main function
int main()
{
    char infix[MAX], postfix[MAX];

    printf("Enter infix expression: ");
    scanf("%s", infix);

    infixToPostfix(infix, postfix);

    printf("Postfix expression: %s\n", postfix);

    return 0;
}




Editor is loading...
Leave a Comment