Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Please answer using pseudocode cormen chapter 2 class Stack { constructor ( ) { this.items = [ ] ; } push ( element ) {

Please answer using pseudocode cormen chapter2
class Stack {
constructor(){
this.items =[];
}
push(element){
this.items.push(element);
}
pop(){
if (this.isEmpty()) return "Underflow";
return this.items.pop();
}
peek(){
return this.items[this.items.length -1];
}
isEmpty(){
return this.items.length ===0;
}
}
class PostfixEvaluator {
constructor(){
this.stack = new Stack();
this.variables ={};
}
evaluatePostfix(expression){
const tokens = expression.split('');
for (let i =0; i < tokens.length; i++){
const token = tokens[i];
if (!isNaN(parseFloat(token))){
this.stack.push(parseFloat(token));
} else if (token in this.variables){
this.stack.push(this.variables[token]);
} else if (this.isOperator(token)){
const operand2= this.stack.pop();
const operand1= this.stack.pop();
const result = this.calculate(token, operand1, operand2);
this.stack.push(result);
} else if (token !=='='){
throw new Error('Invalid token: '+ token);
}
}
return this.stack.pop();
}
isOperator(token){
return token ==='+'|| token ==='-'|| token ==='*'|| token ==='/';
}
calculate(operator, operand1, operand2){
switch (operator){
case '+':
return operand1+ operand2;
case '-':
return operand1- operand2;
case '*':
return operand1* operand2;
case '/':
if (operand2===0) throw new Error('Division by zero');
return operand1/ operand2;
default:
throw new Error('Invalid operator');
}
}
setVariable(name, value){
this.variables[name]= value;
}
}

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Big Data, Mining, And Analytics Components Of Strategic Decision Making

Authors: Stephan Kudyba

1st Edition

1466568704, 9781466568709

More Books

Students also viewed these Databases questions