Professional Documents
Culture Documents
#include <iostream>
#include <stack>
#include <string>
struct Node {
char data;
Node* next;
};
class Stack {
private:
Node* top;
public:
Stack() {
top = nullptr;
}
void push(char c) {
Node* newNode = new Node;
newNode->data = c;
newNode->next = top;
top = newNode;
}
char pop() {
if (isEmpty()) {
return '\0';
}
Node* temp = top;
char c = temp->data;
top = top->next;
delete temp;
return c;
}
bool isEmpty() {
return top == nullptr;
}
char peek() {
if (isEmpty()) {
return '\0';
}
return top->data;
}
};
bool isOperator(char c) {
return (c == '+' || c == '-' || c == '*' || c == '/');
}
int getPrecedence(char c) {
switch (c) {
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
default:
return 0;
}
}
while (!stack.isEmpty()) {
postfix += stack.pop();
}
return postfix;
}
if (isalnum(c)) {
prefix = c + prefix;
} else if (c == ')') {
stack.push(c);
} else if (c == '(') {
while (!stack.isEmpty() && stack.peek() != ')') {
prefix = stack.pop() + prefix;
}
stack.pop();
} else if (isOperator(c)) {
while (!stack.isEmpty() && getPrecedence(c) < getPrecedence(stack.peek())) {
prefix = stack.pop() + prefix;
}
stack.push(c);
}
}
while (!stack.isEmpty()) {
prefix = stack.pop() + prefix;
}
return prefix;
}
int main() {
string infix;
int choice;
string result;
if (choice == 1) {
result = infixToPostfix(infix);
cout << "Postfix expression: " << result << endl;
} else if (choice == 2) {
result = infixToPrefix(infix);
cout << "Prefix expression: " << result << endl;
} else {
cout << "Invalid choice." << endl;
}
return 0;
}