File tree Expand file tree Collapse file tree 1 file changed +82
-0
lines changed
Expand file tree Collapse file tree 1 file changed +82
-0
lines changed Original file line number Diff line number Diff line change 1+ #include <stdio.h>
2+ #include <ctype.h>
3+ #include <string.h>
4+
5+ #define MAX 100
6+
7+ char stack[MAX];
8+ int top = -1;
9+
10+ void push(char c) {
11+ if (top == MAX - 1) {
12+ printf("Stack Overflow\n");
13+ return;
14+ }
15+ stack[++top] = c;
16+ }
17+
18+ char pop() {
19+ if (top == -1) {
20+ printf("Stack Underflow\n");
21+ return -1;
22+ }
23+ return stack[top--];
24+ }
25+
26+ int precedence(char op) {
27+ if (op == '^')
28+ return 3;
29+ if (op == '*' || op == '/')
30+ return 2;
31+ if (op == '+' || op == '-')
32+ return 1;
33+ return 0;
34+ }
35+
36+ int isOperator(char c) {
37+ return (c == '+' || c == '-' || c == '*' || c == '/' || c == '^');
38+ }
39+
40+ void infixToPostfix(char infix[]) {
41+ char postfix[MAX];
42+ int j = 0;
43+ for (int i = 0; i < strlen(infix); i++) {
44+ char c = infix[i];
45+
46+ if (isalnum(c)) {
47+ postfix[j++] = c;
48+ }
49+ else if (c == '(') {
50+ push(c);
51+ }
52+ else if (c == ')') {
53+ while (top != -1 && stack[top] != '(') {
54+ postfix[j++] = pop();
55+ }
56+ pop(); // remove '('
57+ }
58+ else if (isOperator(c)) {
59+ while (top != -1 && precedence(stack[top]) >= precedence(c)) {
60+ postfix[j++] = pop();
61+ }
62+ push(c);
63+ }
64+ }
65+
66+ while (top != -1) {
67+ postfix[j++] = pop();
68+ }
69+ postfix[j] = '\0';
70+
71+ printf("Postfix Expression: %s\n", postfix);
72+ }
73+
74+ int main() {
75+ char infix[MAX];
76+ printf("Enter an infix expression: ");
77+ scanf("%s", infix);
78+
79+ infixToPostfix(infix);
80+
81+ return 0;
82+ }
You can’t perform that action at this time.
0 commit comments