-
Notifications
You must be signed in to change notification settings - Fork 0
/
Infix2PostfixConverter.cs
60 lines (59 loc) · 2.06 KB
/
Infix2PostfixConverter.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
using System.Collections.Generic;
using System.Linq;
public class Infix2PostfixConverter
{
private List<MathOperator> operators;
public Infix2PostfixConverter()
{
CreateOperators();
postFix = "";
}
public string Convert(string expression)
{
var postFix = "";
var operatorsStack = new GenericStack<MathOperator>();
var operandsStack = new GenericStack<string>();
var operand = "";
foreach (var letter in expression)
{
if (IsOperator(letter))
{
operandsStack.Insert(operand);
postFix += operand + " ";
operand = string.Empty;
var mathOperator = GetOperator(letter);
if (!OperatorHasPriorityInStack(mathOperator, operatorsStack))
while (!operatorsStack.IsEmpty())
postFix += operatorsStack.Pop().GetSymbol() + " ";
operatorsStack.Insert(mathOperator);
}
else
operand += letter.ToString();
}
if (!string.IsNullOrEmpty(operand))
postFix += operand + " ";
while (!operatorsStack.IsEmpty())
postFix += operatorsStack.Pop().GetSymbol() + " ";
return postFix;
}
private void CreateOperators()
{
operators = new List<MathOperator>();
operators.Add(new MathOperator("+", 1));
operators.Add(new MathOperator("-", 1));
operators.Add(new MathOperator("*", 2));
operators.Add(new MathOperator("/", 2));
}
private bool IsOperator(char letter)
{
return operators.Any(x => x.GetSymbol() == letter.ToString());
}
private MathOperator GetOperator(char letter)
{
return operators.FirstOrDefault(x => x.GetSymbol() == letter.ToString());
}
private bool OperatorHasPriorityInStack(MathOperator mathOperator, GenericStack<MathOperator> operatorsStack)
{
return operatorsStack.IsEmpty() || mathOperator.GetPriority() > operatorsStack.Top().GetValue().GetPriority();
}
}