递归的代码比迭代的代码看起来更清爽一些,也是因为递归对行为进行了抽象吧。
注意到,这是一个尾递归函数,一些编译器会将它优化为迭代,这样一方面,在代码层面保持了清晰的逻辑和可读性,一方面保持了代码的性能。
代码:
class Solution
{
public:
ListNode* reverseList(ListNode* head)
{
// return iteratively(head);
return recursively(nullptr, head);
}
private:
ListNode* iteratively(ListNode *head)
{
auto cur = head;
for (ListNode* pre = nullptr; cur != nullptr;)
{
if (cur->next == nullptr)
{
cur->next = pre;
return cur;
} else
{
swap(pre, cur->next);
swap(pre, cur);
}
}
return nullptr;
}
// note that this tail recursive algo should be transformed into iterate algo to obtain the better performance
ListNode* recursively(ListNode *pre, ListNode *cur)
{
if (cur == nullptr)
{
return pre;
} else
{
swap(pre, cur->next);
return recursively(cur, pre);
}
}
};