forked from dimpeshmalviya/C-Language-Programs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStack-Infix-To-Postfix.cpp
More file actions
104 lines (86 loc) · 2.01 KB
/
Stack-Infix-To-Postfix.cpp
File metadata and controls
104 lines (86 loc) · 2.01 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
#include <stdio.h>
#include <ctype.h> // for isalpha, isdigit
#include <string.h>
#define MAX 100
// Stack structure
char stack[MAX];
int top = -1;
// Push operation
void push(char c) {
if (top < MAX - 1) {
stack[++top] = c;
}
}
// Pop operation
char pop() {
if (top >= 0)
return stack[top--];
return '\0';
}
// Peek top element
char peek() {
if (top >= 0)
return stack[top];
return '\0';
}
// Check if operator
int isOperator(char c) {
return (c == '+' || c == '-' || c == '*' || c == '/' || c == '^');
}
// Precedence of operators
int precedence(char c) {
switch (c) {
case '^': return 3;
case '*':
case '/': return 2;
case '+':
case '-': return 1;
default: return 0;
}
}
// Convert infix to postfix
void infixToPostfix(char infix[], char postfix[]) {
int i, j = 0;
char c;
for (i = 0; infix[i] != '\0'; i++) {
c = infix[i];
// If operand, add to postfix output
if (isalnum(c)) {
postfix[j++] = c;
postfix[j++] = ' '; // space for clarity
}
// If '(', push to stack
else if (c == '(') {
push(c);
}
// If ')', pop until '('
else if (c == ')') {
while (top != -1 && peek() != '(') {
postfix[j++] = pop();
postfix[j++] = ' ';
}
pop();
}
else if (isOperator(c)) {
while (top != -1 && precedence(peek()) >= precedence(c)) {
postfix[j++] = pop();
postfix[j++] = ' ';
}
push(c);
}
}
// Pop remaining operators
while (top != -1) {
postfix[j++] = pop();
postfix[j++] = ' ';
}
postfix[j - 1] = '\0';
}
int main() {
char infix[MAX], postfix[MAX];
printf("Enter infix expression: ");
gets(infix);
infixToPostfix(infix, postfix);
printf("Postfix Expression: %s\n", postfix);
return 0;
}