DSA 13
DSA 13
newNode->data = value;
newNode->next = s->top;
s->top = newNode;
}
// Function to pop an element from the stack
int pop(struct Stack* s) {
if (isEmpty(s)) {
printf("Stack underflow\n");
exit(EXIT_FAILURE);
}
int value = s->top->data;
struct Node* temp = s->top;
s->top = s->top->next;
free(temp);
return value;
}
// Function to evaluate an arithmetic expression in postfix notation
int evaluatePostfix(char postfix[]) {
struct Stack stack;
initialize(&stack);
int i, operand1, operand2, result;
char ch;
for (i = 0; postfix[i] != '\0'; i++) {
ch = postfix[i];
if (isdigit(ch)) {
push(&stack, ch - '0'); // Convert character to integer and push onto the stack
} else {
operand2 = pop(&stack);
operand1 = pop(&stack);
switch (ch) {
case '+':
result = operand1 + operand2;
break;
case '-':
result = operand1 - operand2;
break;
case '*':
result = operand1 * operand2;
break;
case '/':
if (operand2 != 0) {
result = operand1 / operand2;
} else {
printf("Division by zero\n");
exit(EXIT_FAILURE);
}
break;
default:
printf("Invalid operator\n");
exit(EXIT_FAILURE);
}
push(&stack, result);
}
}
if (!isEmpty(&stack)) {
result = pop(&stack);
if (isEmpty(&stack)) {
return result;
} else {
printf("Invalid expression\n");
exit(EXIT_FAILURE);
}
} else {
printf("Invalid expression\n");
exit(EXIT_FAILURE);
}
}
int main() {
char postfix[100];
printf("Name :- Varun\nRoll no.- 221901258\n");
printf("Enter a postfix expression: ");
gets(postfix);
int result = evaluatePostfix(postfix);
printf("Result: %d\n", result);
return 0;
}
Output: