You are on page 1of 4

Bangladesh University of Business and Technology

Lab Report: 8

Dept. name: Computer Science and Engineering

Course name: Data Structure Lab

Course code: CSE 232

Submitted By: Rafsan Samin


22234103208

Submitted To: Md. Mahbub-Or-Rashid


Assistant professor,
Dept. of Computer Science and Engineering

Submission Date: 11-12-2023


Stack Implementation Ifix to postfix and Ackermaan function

#include <iostream>
#include <stack>
#include <string>

class Stack {
private:
std::stack<char> data;

public:
void push(char c) {
data.push(c);
}

char pop() {
char c = data.top();
data.pop();
return c;
}

char top() {
return data.top();
}

bool isEmpty() {
return data.empty();
}

int size() {
return data.size();
}
};

bool isOperator(char c) {
return (c == '+' || c == '-' || c == '*' || c == '/');
}

int getPrecedence(char op) {


if (op == '+' || op == '-') return 1;
if (op == '*' || op == '/') return 2;
return 0;
}

std::string infixToPostfix(const std::string& infix) {


std::string postfix = "";
Stack stack;
for (char c : infix) {
if (isalnum(c)) {
postfix += c;
} else if (c == '(') {
stack.push(c);
} else if (c == ')') {
while (!stack.isEmpty() && stack.top() != '(') {
postfix += stack.pop();
}
stack.pop(); // Pop the '('
} else if (isOperator(c)) {
while (!stack.isEmpty() && getPrecedence(c) <= getPrecedence(stack.top())) {
postfix += stack.pop();
}
stack.push(c);
}
}
while (!stack.isEmpty()) {
postfix += stack.pop();
}
return postfix;
}

int ackermann(int m, int n) {


if (m == 0) return n + 1;
if (m > 0 && n == 0) return ackermann(m - 1, 1);
if (m > 0 && n > 0) return ackermann(m - 1, ackermann(m, n - 1));
}

int main() {
std::string infix = "2+3*4";
std::string postfix = infixToPostfix(infix);
std::cout << "Infix: " << infix << std::endl;
std::cout << "Postfix: " << postfix << std::endl;

int result = ackermann(3, 4);


std::cout << "Ackermann(3, 4) = " << result << std::endl;

return 0;
}

Output:
Infix: 2+3*4
Postfix: 234*+
Ackermann(3, 4) = 125

You might also like