如何将递归函数转换为迭代函数
我正在尝试使用堆栈将此递归函数转换为迭代函数:
void GetToTownRecursive(int x, Country &country, AList *accessiblesGroup, vector<eTownColor> &cities_colors)
{
cities_colors[x - 1] = eTownColor::BLACK;
accessiblesGroup->Insert(x);
List *connected_cities = country.GetConnectedCities(x);
if (!connected_cities->IsEmpty())
{
ListNode *curr_city = connected_cities->First();
while (curr_city != nullptr)
{
if (cities_colors[curr_city->GetTown() - 1] == eTownColor::WHITE)
{
GetToTownRecursive(curr_city->GetTown(), country, accessiblesGroup, cities_colors);
}
curr_city = curr_city->GetNextNode();
}
}
}
该函数将城镇编号作为输入,并返回与该城镇连接(直接和间接)的城镇列表。
由于递归调用后采取的唯一操作是提升列表迭代器 - curr_city
,因此我在转换它时遇到了困难。在这种情况下我应该将什么推入堆栈?
很高兴得到您的帮助!
I'm trying to convert this recursive function to an iterative one using a stack:
void GetToTownRecursive(int x, Country &country, AList *accessiblesGroup, vector<eTownColor> &cities_colors)
{
cities_colors[x - 1] = eTownColor::BLACK;
accessiblesGroup->Insert(x);
List *connected_cities = country.GetConnectedCities(x);
if (!connected_cities->IsEmpty())
{
ListNode *curr_city = connected_cities->First();
while (curr_city != nullptr)
{
if (cities_colors[curr_city->GetTown() - 1] == eTownColor::WHITE)
{
GetToTownRecursive(curr_city->GetTown(), country, accessiblesGroup, cities_colors);
}
curr_city = curr_city->GetNextNode();
}
}
}
The function takes a town number as an input and returns a list of towns that are connected to that town (directly as well as indirectly).
I'm having difficulty converting it because of the while loop within and because the only action taken after the recursive call is the promotion of the list iterator - curr_city
. What should I push into the stack in this case?
Would be glad for your help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
递归呼叫后采取的动作是整个While循环的剩余时间(所有剩余的迭代)。在堆栈上,您必须节省任何在递归电话期间可能会更改的变量,但需要之后需要。在这种情况下,这仅仅是
curr_city
的值。如果
goto
仍然是一件事情,则可以用以下方式替换递归调用:curr_city
x = curr_city-&gt; gettown()
,您必须
curr_city
,将其还原并在(3)之后恢复并goto,因为它是不可接受的可接受此类gotos事物(它们使您的代码难以理解),您必须将功能分解为3个顶级部分:
通常,在重新排列后,您可以进行大量的清理和简化。
The action taken after the recursive call is the whole remainder of the while loop (all the remaining iterations). On the stack, you have to save any variables that could change during the recursive call, but will be needed after. In this case, that's just the value of
curr_city
.If
goto
was still a thing, you could then replace the recursive call with:curr_city
x = curr_city->GetTown()
Then at the end, you have to
curr_city
, restore it and goto just after (3)Because it's not acceptable to use gotos for this sort of thing (they make your code hard to understand), you have to break up your function into 3 top-level parts:
Typically there is then a lot of cleanup and simplification you can do after this rearrangement.
基本想法将是以下内容。
The basic idea would be something like the following.