Untitled

 avatar
unknown
plain_text
2 years ago
2.2 kB
5
Indexable
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

#define STACK_SIZE 100

typedef struct {
    int data[STACK_SIZE];
    int top;
} Stack;

void initializeStack(Stack *stack) {
    stack->top = -1;
}

int isEmpty(Stack *stack) {
    return stack->top == -1;
}

int isFull(Stack *stack) {
    return stack->top == STACK_SIZE - 1;
}

void push(Stack *stack, int value) {
    if (!isFull(stack)) {
        stack->top++;
        stack->data[stack->top] = value;
    }
}

int pop(Stack *stack) {
    if (!isEmpty(stack)) {
        int value = stack->data[stack->top];
        stack->top--;
        return value;
    }
    return 0; // Return some default value (0) indicating an error
}

int evaluatePostfixExpression(const char *expression) {
    Stack stack;
    initializeStack(&stack);

    int i = 0;
    char *token;
    const char delimiter[] = ", ";
    token = strtok(expression, delimiter);

    while (token != NULL) {
        if (isdigit(token[0])) {
            push(&stack, atoi(token));
        } else {
            int operand2 = pop(&stack);
            int operand1 = pop(&stack);

            switch (token[0]) {
                case '+':
                    push(&stack, operand1 + operand2);
                    break;
                case '-':
                    push(&stack, operand1 - operand2);
                    break;
                case '*':
                    push(&stack, operand1 * operand2);
                    break;
                case '/':
                    push(&stack, operand1 / operand2);
                    break;
                // Add other operators here if needed
            }
        }

        token = strtok(NULL, delimiter);
    }

    return pop(&stack);
}

int main() {
    char expression[100];
    printf("Enter the postfix expression: ");
    fgets(expression, sizeof(expression), stdin);

    // Remove the trailing newline character from fgets
    int len = strlen(expression);
    if (len > 0 && expression[len - 1] == '\n') {
        expression[len - 1] = '\0';
    }

    int result = evaluatePostfixExpression(expression);
    printf("Result: %d\n", result);

    return 0;
}
Editor is loading...