我正在开发一个二叉搜索树控制台应用程序,特别是一种列出两个目标节点之间最短路径的方法。我的方法是
1) 创建树中从根节点到目标的每个目标节点的值的 ArrayList(每个路径一个 ArrayList) 2) 比较两个 ArrayList,删除除最后一个之外的所有重复项(这将表示两个路径分支 3) 将剩余的两个 ArrayList 组合成一个数组并使用 for 循环打印到控制台
这是我正在使用的方法。我遇到的问题是我永远不会进入读取“if (list1[n] == list2[n])”的块,即使 ArrayLists 正在打印出 _pathArrayList1 的值 Contents: 5, 7 , 9 _pathArrayList2 的内容: 5, 7, 9, 10, 12, 11
我尝试了打字,但这没有帮助。
array<T>^ removeDuplicates(ArrayList^ list1, ArrayList^ list2)
{
int forLoopCount;
int i; // for loop iterator for this method
Console::WriteLine(L"Contents of _pathArrayList1: ");
for (i = 0; i < list1->Count; i++)
Console::WriteLine(list1[i]);
Console::WriteLine(L"Contents of _pathArrayList2");
for (i = 0; i < list2->Count; i++)
Console::WriteLine(list2[i]);
// find out which array is the shortest; we need to use the shorter of the two
if (list1->Count - list2->Count < 0)
forLoopCount = list1->Count;
else
forLoopCount = list2->Count;
Console::WriteLine("Value of forLoopCopunt is " + forLoopCount);
array<T>^ combineArray = gcnew array<T>(forLoopCount);
for (int n = 0; n < forLoopCount; n++)
{
Console::WriteLine(L"List1[n] = " + list1[n]);
Console::WriteLine(L"list2[n] = " + list2[n]);
if (list1[n] == list2[n]) // never entering this block of code
{
if (list2[n+1] == list1[n+1])
{
Console::WriteLine(L"Removing " + list1[n] + " and " + list2[n]);
list1->RemoveAt(n);
list2->RemoveAt(n);
n --;
}
else
{
Console::WriteLine(L"Deleting " + list1[n]);
list1->RemoveAt(n);
//_pathArrayList1->Reverse();
return combineArray = combineArrays(_pathArrayList1, _pathArrayList2);
}
}
}
return combineArray = combineArrays(_pathArrayList1, _pathArrayList2);
}