Question: import 'dart:io ' ; int evaluatePrefix ( String expression ) { List stack = [ ] ; / / Traverse the expression from right to

import 'dart:io'; int evaluatePrefix(String expression){ List stack =[]; // Traverse the expression from right to left for (int i = expression.length -1; i >=0; i--){ String char = expression[i]; if (RegExp(r'[0-9]').hasMatch(char)){// Push operands onto the stack stack.add(int.parse(char)); } else if ('+*/-'.contains(char)){// Pop two operands for evaluation int operand1= stack.removeLast(); int operand2= stack.removeLast(); int result =0; switch (char){ case '+': result = operand1+ operand2; break; case '-': result = operand1- operand2; break; case '*': result = operand1* operand2; break; case '/': result = operand1 ~/ operand2; // Integer division break; }// Push the result back onto the stack stack.add(result); }}// The result is the last remaining value on the stack return stack.last; } void main(){ String? input = stdin.readLineSync(); if (input != null && input.isNotEmpty){ print(evaluatePrefix(input)); }}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!