我想在C#中實現二叉搜索樹,並遵循Cormen等人的第12章來完成。要做到這一點,我需要使用可空類型,像這樣:使用可空整數訪問數組
public int insert(Node newNode) // return array index of added node
{
int? y = null;
int? x = this.root;
while (x != null)
{
y = (int)x;
if (newNode.key < this.tree[x])
{ }
}
return 0;
}
現在我得到以下錯誤:
Cannot implicitly convert type 'int?' to 'int'. An explicit conversion exists (are you missing a cast)?
對於這個if (newNode.key < this.tree[x])
線。
使用可爲空的類型來訪問數組索引是非法的嗎?
我可以用不同的方式初始化數組嗎?
或者我應該忘記null並且使用-1作爲例子嗎?
參考['Nullable'類型](https://msdn.microsoft.com /en-us/library/1t3y8s4s.aspx),並確保它後嘗試'x.Value'我s不爲null。 – Alex
如果你想真正學習數據結構和算法,我會建議在非託管環境中進行這項練習。 –
@ aj.toulan:爲什麼?大多數(如果不是所有的)通用算法都可以在管理環境中很好地實現。作爲一個好處,您可以專注於實際算法,而不必擔心正確管理內存。 –