LeetCode 206. Reverse Linked List(迭代和递归两种实现)

递归的代码比迭代的代码看起来更清爽一些,也是因为递归对行为进行了抽象吧。

注意到,这是一个尾递归函数,一些编译器会将它优化为迭代,这样一方面,,在代码层面保持了清晰的逻辑和可读性,一方面保持了代码的性能。

代码:

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 performanceListNode* recursively(ListNode *pre, ListNode *cur){if (cur == nullptr){return pre;} else{swap(pre, cur->next);return recursively(cur, pre);}}};

版权声明:本文为博主原创文章,未经博主允许不得转载。

从起点,到尽头,也许快乐,或有时孤独,

LeetCode 206. Reverse Linked List(迭代和递归两种实现)

相关文章:

你感兴趣的文章:

标签云: