直接上代码
public static class InfixToPostfix
{
private static List<char> highOperator = new List<char> { '*', '/' };
private static List<char> lowOperator = new List<char> { '+', '-' };
public static string Method(string str)
{
var stack = new Stack<char>();
var ans = new StringBuilder();
foreach (char item in str)
{
if (item >= 48 && item <= 57)
{
ans.Append(item);
}
else if (item == '(')
{
stack.Push(item);
}
else if (item == ')')
{
while (stack.Count > 0)
{
var preOpe = stack.Pop();
if (preOpe == '(')
{
break;
}
ans.Append(preOpe);
}
}
else // 操作符
{
if (stack.Count != 0)
{
var preOpe = stack.Peek();
// 栈顶操作符优先级大于等于当前操作符优先级
if ((highOperator.Contains(preOpe) && highOperator.Contains(item))
|| (highOperator.Contains(preOpe) && lowOperator.Contains(item)))
{
ans.Append(stack.Pop());
}
}
stack.Push(item);
}
}
while (stack.Count > 0)
{
ans.Append(stack.Pop());
}
return ans.ToString();
}
}
网友评论