-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInfix_To_Postfix.cpp
104 lines (85 loc) · 2.37 KB
/
Infix_To_Postfix.cpp
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
// Write a program in cpp to convert an infix expression into a postfix expression by implementing stack.
#include <iostream>
#include <cctype>
class Stack {
private:
int maxSize;
int top;
char* stackArray;
public:
Stack(int size) : maxSize(size), top(-1) {
stackArray = new char[maxSize];
}
~Stack() {
delete[] stackArray;
}
void push(char value) {
if (top < maxSize - 1) {
stackArray[++top] = value;
} else {
std::cerr << "Stack overflow\n";
}
}
char pop() {
if (top >= 0) {
return stackArray[top--];
} else {
std::cerr << "Stack underflow\n";
return '\0';
}
}
char peek() const {
if (top >= 0) {
return stackArray[top];
} else {
std::cerr << "Stack is empty\n";
return '\0';
}
}
bool isEmpty() const {
return top == -1;
}
};
bool isOperator(char ch) {
return (ch == '+' || ch == '-' || ch == '*' || ch == '/');
}
int getPrecedence(char op) {
if (op == '+' || op == '-')
return 1;
else if (op == '*' || op == '/')
return 2;
return 0;
}
std::string infixToPostfix(const std::string& infix) {
std::string postfix;
Stack operatorStack(infix.size());
for (char ch : infix) {
if (std::isalnum(ch)) {
postfix += ch;
} else if (isOperator(ch)) {
while (!operatorStack.isEmpty() && getPrecedence(operatorStack.peek()) >= getPrecedence(ch)) {
postfix += operatorStack.pop();
}
operatorStack.push(ch);
} else if (ch == '(') {
operatorStack.push(ch);
} else if (ch == ')') {
while (!operatorStack.isEmpty() && operatorStack.peek() != '(') {
postfix += operatorStack.pop();
}
operatorStack.pop(); // This is to Pop the opening parenthesis
}
}
while (!operatorStack.isEmpty()) {
postfix += operatorStack.pop();
}
return postfix;
}
int main() {
std::string infixExpression;
std::cout << "Enter infix expression: ";
std::getline(std::cin, infixExpression);
std::string postfixExpression = infixToPostfix(infixExpression);
std::cout << "Postfix expression: " << postfixExpression << std::endl;
return 0;
}