-3
我正在從中綴表達式構建表達式樹。目前我正在轉換爲後綴,然後構建樹。我的代碼適用於大多數表達式,但不是全部。我在執行括號時出錯。這裏是我的代碼 -C#中的調車場算法僅適用於部分時間
readonly static char[] operators = { '+', '-', '*', '/' };
string order_of_op(string op1, string op2)
{
if (op1 == "*" || op1 == "/")//is op1 higher?
{
return op1;//it is so return it
}
else if ((op2 == "*" || op2 == "/"))//is op2 higher
{
return op2;//it is so return it
}
else
return op1;// they are both addition or subtraction so return op1.
}
Queue<string> convert_to_postfix(string infix) //following the Shunting-yard algorithm
{
Queue<string> num_queue = new Queue<string>();
Stack<string> op_stack = new Stack<string>();
Stack<string> temp_stack = new Stack<string>();
string temp = "";
foreach (char s in infix)
{
if (operators.Contains(s) == true)//if its a function push it on the stack
{
if (temp != "")//make sure we don't push an empty string
num_queue.Enqueue(temp);
if (op_stack.Count != 0)//make sure we dont crash popping from empty stack
{
if (op_stack.Peek() != "(")//if we dont have a parenthese on top proceed as normal
{
if (op_stack.Count > 1)
{
while (op_stack.Count != 0 && order_of_op(op_stack.Peek(), s.ToString()) == op_stack.Peek())
{
num_queue.Enqueue(op_stack.Pop());
}
}
}
op_stack.Push(s.ToString());
}
else
{
op_stack.Push(s.ToString());
}
temp = "";
}
else if (s == '(')
{
op_stack.Push(s.ToString());
}
else if (s == ')')
{
if (temp!= "")
num_queue.Enqueue(temp);
temp = "";
while (op_stack.Peek() != "(")
{
num_queue.Enqueue(op_stack.Pop());
}
op_stack.Pop();
if (op_stack.Count > 1)
{
if (operators.Contains(op_stack.Peek()[0]) == true)
{
num_queue.Enqueue(op_stack.Pop());
}
}
}
else
{
temp += s;
}
}
if (temp != "")
{
num_queue.Enqueue(temp);
}
foreach (string s in op_stack)
{
num_queue.Enqueue(s);
}
Console.Write("Postfix = ");
foreach (string s in num_queue)
{
Console.Write(s);
}
Console.WriteLine();
return num_queue;
}
謝謝任何幫助!
歡迎stackoverflow.com。請花些時間閱讀[幫助頁面](http://stackoverflow.com/help),尤其是名爲[「我可以問些什麼話題?」]的章節(http://stackoverflow.com/help/)討論話題)和[「我應該避免問什麼類型的問題?」](http://stackoverflow.com/help/dont-ask)。另請[請閱讀如何提出好問題](http://stackoverflow.com/help/how-to-ask)。您可能還想了解如何創建[最小,完整和可驗證示例](http://stackoverflow.com/help/mcve)。 – wimh
什麼不起作用?請儘可能簡單地回答我們的工作。 – Enigmativity
如果您提供了一些示例輸入數據以及代碼是如何運行的,那也會很好。你的代碼也不能編譯。它缺少'運營商'的聲明。現在正在爲我們開展很多工作。請讓它更容易。 – Enigmativity