-
Notifications
You must be signed in to change notification settings - Fork 0
/
46john18.c
86 lines (78 loc) · 2.31 KB
/
46john18.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
/*
Roll no:46
Batch:B
Author Name:John Joy
Date:2/09/23
Description: Program for Expression Evaluation
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
// Define a stack data structure to help with the evaluation
struct Stack {
int top;
unsigned capacity;
int* array;
};
// Create and initialize a stack
struct Stack* createStack(unsigned capacity) {
struct Stack* stack = (struct Stack*)malloc(sizeof(struct Stack));
stack->capacity = capacity;
stack->top = -1;
stack->array = (int*)malloc(stack->capacity * sizeof(int));
return stack;
}
// Check if the stack is empty
int isEmpty(struct Stack* stack) {
return stack->top == -1;
}
// Push an element onto the stack
void push(struct Stack* stack, int item) {
stack->array[++stack->top] = item;
}
// Pop an element from the stack
int pop(struct Stack* stack) {
if (!isEmpty(stack))
return stack->array[stack->top--];
return -1; // Return -1 for empty stack (error condition)
}
// Evaluate the given postfix expression
int evaluatePostfix(char* exp) {
struct Stack* stack = createStack(strlen(exp));
int i;
// Iterate through the expression
for (i = 0; exp[i]; ++i) {
// If the current character is a digit, push it onto the stack
if (isdigit(exp[i]))
push(stack, exp[i] - '0');
else {
// If it's 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 (exp[i]) {
case '+':
push(stack, operand1 + operand2);
break;
case '-':
push(stack, operand1 - operand2);
break;
case '*':
push(stack, operand1 * operand2);
break;
case '/':
push(stack, operand1 / operand2);
break;
}
}
}
// The final result should be on the top of the stack
return pop(stack);
}
int main() {
char exp[] = "62+2/3+";
printf("Expression: %s\n", exp);
printf("Result: %d\n", evaluatePostfix(exp));
return 0;
}