-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStackOperations.c
More file actions
61 lines (53 loc) · 1.35 KB
/
Copy pathStackOperations.c
File metadata and controls
61 lines (53 loc) · 1.35 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
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#define MAX 100
// Stack Structure
int stack[MAX];
int top = -1;
void push(int value) {
if (top == MAX - 1) printf("Stack Overflow\n");
else stack[++top] = value;
}
int pop() {
if (top == -1) { printf("Stack Underflow\n"); return -1; }
else return stack[top--];
}
void peek() {
if (top == -1) printf("Stack is empty\n");
else printf("Top element: %d\n", stack[top]);
}
// Precedence helper for Infix to Postfix
int precedence(char c) {
if (c == '+' || c == '-') return 1;
if (c == '*' || c == '/') return 2;
return 0;
}
void infixToPostfix(char* infix) {
char postfix[MAX];
int p = 0;
for (int i = 0; infix[i] != '\0'; i++) {
if (isalnum(infix[i])) postfix[p++] = infix[i];
else if (infix[i] == '(') push('(');
else if (infix[i] == ')') {
while (top != -1 && stack[top] != '(') postfix[p++] = pop();
pop();
} else {
while (top != -1 && precedence(stack[top]) >= precedence(infix[i]))
postfix[p++] = pop();
push(infix[i]);
}
}
while (top != -1) postfix[p++] = pop();
postfix[p] = '\0';
printf("Postfix: %s\n", postfix);
}
int main() {
// Example usage
push(10);
push(20);
peek();
pop();
infixToPostfix("a+b*c");
return 0;
}