evaluate postfix expression
unknown
c_cpp
2 years ago
2.8 kB
13
Indexable
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
// Structure to represent a stack
struct Stack {
int* array;
int top;
};
// Function to initialize an empty stack
void initializeStack(struct Stack* stack, int size) {
stack->array = (int*)malloc(size * sizeof(int));
stack->top = -1;
}
// Function to check if the stack is empty
int isEmpty(struct Stack* stack) {
return (stack->top == -1);
}
// Function to push an element onto the stack
void push(struct Stack* stack, int value) {
stack->array[++stack->top] = value;
}
// Function to pop an element from the stack
int pop(struct Stack* stack) {
if (!isEmpty(stack)) {
return stack->array[stack->top--];
}
return -1; // Return -1 for an empty stack (assuming all operands are positive integers)
}
// Function to evaluate a postfix expression
int evaluatePostfix(char* postfix) {
struct Stack stack;
initializeStack(&stack, 100); // Assuming a maximum size of 100 for the stack
for (int i = 0; postfix[i] != '\0'; i++) {
char currentChar = postfix[i];
if (isdigit(currentChar)) {
// If the current character is a digit, convert it to an integer and push onto the stack
push(&stack, currentChar - '0');
} else {
// If the current character is an operator, pop two operands from the stack,
// perform the operation, and push the result back onto the stack
int operand2 = pop(&stack);
int operand1 = pop(&stack);
switch (currentChar) {
case '+':
push(&stack, operand1 + operand2);
break;
case '-':
push(&stack, operand1 - operand2);
break;
case '*':
push(&stack, operand1 * operand2);
break;
case '/':
if (operand2 != 0) {
push(&stack, operand1 / operand2);
} else {
printf("Error: Division by zero\n");
return -1; // Error: Division by zero
}
break;
default:
printf("Error: Invalid operator\n");
return -1; // Error: Invalid operator
}
}
}
// The final result should be on the top of the stack
return pop(&stack);
}
// Main function to test postfix expression evaluation
int main() {
char postfixExpression[100];
printf("Enter a postfix expression: ");
scanf("%s", postfixExpression);
int result = evaluatePostfix(postfixExpression);
if (result != -1) {
printf("Result of the postfix expression: %d\n", result);
}
return 0;
}Editor is loading...
Leave a Comment