adspace
Write a program to convert postfix expression to infix
expression.
Answer Posted / Ekta Agrawal
[C# code example:]
using System;
using System.Collections.Generic;
using System.Linq;
public class PostfixToInfix {
private static double EvaluatePostfix(Stack<double> stack, string postfix) {
var tokens = postfix.Split(' ');
foreach (var token in tokens) {
if (!double.TryParse(token, out double value)) {
switch (token[0]) {
case '+':
stack.Push(stack.Pop() + stack.Pop());
break;
case '-':
stack.Push(-stack.Pop() + stack.Pop());
break;
case '*':
stack.Push(stack.Pop() * stack.Pop());
break;
case '/':
double dividend = stack.Pop();
double divisor = stack.Pop();
stack.Push(dividend / divisor);
break;
}
} else {
stack.Push(double.Parse(token));
}
}
return stack.Pop();
}
public static string InfixToPostfix(string infix) {
var operators = new List<char> { '+', '-', '*', '/' };
var precedences = new Dictionary<char, int> { { '+', 1 }, { '-', 1 }, { '*', 2 }, { '/', 2 } };
var postfix = new Stack<string>();
var tokens = infix.Split(' ');
var operandStack = new Stack<string>();
foreach (var token in tokens) {
if (char.IsDigit(token[0])) {
postfix.Push(token);
} else if (operators.Contains(token[0])) {
while (operandStack.Count > 0 && precedences[operandStack.Peek()[0]] >= precedences[token[0]]) {
postfix.Push(" "+ operandStack.Pop() + " ");
}
operandStack.Push(token);
} else if (token == "(") {
operandStack.Push(token);
} else if (token == ")") {
while (operandStack.Peek() != "(") {
postfix.Push(" "+ operandStack.Pop() + " ");
}
operandStack.Pop();
}
}
while (operandStack.Count > 0) {
postfix.Push(" "+ operandStack.Pop() + " ");
}
return string.Join("", postfix);
}
public static void Main() {
var infix = "( 3 + ( 4 * 5 ) )";
Console.WriteLine($"Infix expression: {infix}");
Console.WriteLine($"Postfix expression: {InfixToPostfix(infix)}");
var postfix = "3 4 5 * +"";
double result = EvaluatePostfix(new Stack<double>(), postfix);
Console.WriteLine($"Result: {result}");
}
}
| Is This Answer Correct ? | 0 Yes | 0 No |
Post New Answer View All Answers
No New Questions to Answer in this Category !! You can
Post New Questions
Answer Questions in Different Category