-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStack.c
More file actions
133 lines (113 loc) · 2.81 KB
/
Stack.c
File metadata and controls
133 lines (113 loc) · 2.81 KB
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define MAX_SIZE 100
// Stack structure
typedef struct {
int top;
char items[MAX_SIZE];
} Stack;
// Function prototypes
void push(Stack *s, char c);
char pop(Stack *s);
int isOperator(char c);
int precedence(char c);
void infixToPostfix(char infix[], char postfix[]);
int evaluatePostfix(char postfix[]);
int main() {
char infix[MAX_SIZE], postfix[MAX_SIZE];
printf("Enter an infix expression: ");
fgets(infix, MAX_SIZE, stdin);
infixToPostfix(infix, postfix);
printf("Postfix expression: %s\n", postfix);
int result = evaluatePostfix(postfix);
printf("Result: %d\n", result);
return 0;
}
// Push operation
void push(Stack *s, char c) {
if (s->top == MAX_SIZE - 1) {
printf("Stack Overflow\n");
exit(1);
}
s->items[++(s->top)] = c;
}
// Pop operation
char pop(Stack *s) {
if (s->top == -1) {
printf("Stack Underflow\n");
exit(1);
}
return s->items[(s->top)--];
}
// Check if character is an operator
int isOperator(char c) {
return (c == '+' || c == '-' || c == '*' || c == '/');
}
// Get precedence of operator
int precedence(char c) {
if (c == '+' || c == '-')
return 1;
else if (c == '*' || c == '/')
return 2;
else
return 0;
}
// Convert infix expression to postfix expression
void infixToPostfix(char infix[], char postfix[]) {
Stack s;
s.top = -1;
int i = 0, j = 0;
char c, x;
while ((c = infix[i++]) != '\0') {
if (isalnum(c)) {
postfix[j++] = c;
} else if (c == '(') {
push(&s, c);
} else if (c == ')') {
while ((x = pop(&s)) != '(') {
postfix[j++] = x;
}
} else {
while (precedence(s.items[s.top]) >= precedence(c)) {
postfix[j++] = pop(&s);
}
push(&s, c);
}
}
while (s.top != -1) {
postfix[j++] = pop(&s);
}
postfix[j] = '\0';
}
// Evaluate postfix expression
int evaluatePostfix(char postfix[]) {
Stack s;
s.top = -1;
int i = 0;
char c;
int operand1, operand2;
while ((c = postfix[i++]) != '\0') {
if (isdigit(c)) {
push(&s, c - '0');
} else {
operand2 = pop(&s);
operand1 = pop(&s);
switch (c) {
case '+':
push(&s, operand1 + operand2);
break;
case '-':
push(&s, operand1 - operand2);
break;
case '*':
push(&s, operand1 * operand2);
break;
case '/':
push(&s, operand1 / operand2);
break;
}
}
}
return pop(&s);
}