C# - Evaluate Postfix Expression
C# - Evaluate Postfix Expression
CODE
using System;
using System.Collections.Generic;
class Program
{
public static void Main()
{
try
{
//Provide the postfix expression
string postFixExpression = "2 3 1 * + 9 -";
//initialise the class and call the Evaluate() method
PostFixStack ps = new PostFixStack();
double answer = ps.Evaluate(postFixExpression);
//print the result
Console.WriteLine("{0} = {1}", postFixExpression, answer);
//OUTPUT
//2 3 1 * + 9 - = 4
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
Console.ReadKey();
}
}
class PostFixStack
{
private int top = -1;
private List<string> items = new List<string>();
//Returns true if the Stack is empty
public bool IsEmpty()
{
if (top == -1)
return true;
else
return false;
}
//insert the data to the top of the stack
//the top variable is incremented before inserting the element
public bool Push(string data)
{
top++;
items.Add(data);
return true;
}
//removes and returns the topmost element from the stack
//the top variable is decremented by 1
public string Pop()
{
if (IsEmpty())
{
Console.WriteLine("The Stack is empty.");
return "";
}
else
{
string value = items[top];
items.RemoveAt(top);
top--;
return value;
}
}
public double Evaluate(string postFixExpression)
{
//The operators and operands are expected to be space separated
//split the expression based on space
string[] expressionParts = postFixExpression.Split(' ');
//loop through the splitted parts
foreach (string expressionPart in expressionParts)
{
string expressionPartModified = expressionPart.Trim();
if (expressionPart == "")
continue;
double result;
bool isNumber = double.TryParse(expressionPartModified, out result);
//if it is a number, push it to the stack
if (isNumber)
Push(expressionPartModified);
else
{
//if it is an operator, pop the last 2 items from the stack which will be operands
double val1 = Convert.ToDouble(Pop());
double val2 = Convert.ToDouble(Pop());
///apply the current operator to the last popped values
string currentOperator = expressionPartModified;
switch (currentOperator)
{
case "+":
Push((val1 + val2).ToString());
break;
case "-":
Push((val1 - val2).ToString());
break;
case "*":
Push((val1 * val2).ToString());
break;
case "/":
Push((val1 / val2).ToString());
break;
default:
throw new Exception("Operator '" + currentOperator + "' not supported");
}
}
}
//pop the last available value from the stack which will be the result.
return Convert.ToDouble(Pop());
}
}
Comments
Post a Comment