我自己的方法是用的递归,毕竟也是接触了一点点点点点点 scheme 的骚年是吧,代码如下:
ListNode* reverseList(ListNode* head) { if (head == nullptr){ return nullptr; } ListNode* newHead = nullptr; function<void(ListNode*)> reverse; reverse = [&](ListNode* node) { if (node->next == nullptr){ newHead = node; return; } reverse(node->next); node->next->next = node; node->next = nullptr; }; reverse(head); return newHead; }
毕竟是递归,我琢磨着会不会迭代会快一点,于是有了如下版本:
ListNode* reverseList(ListNode* head) { if (head == nullptr || head->next == nullptr){ return head; } ListNode* previous = head; ListNode* current = head->next; ListNode* next = nullptr; while (current != nullptr){ next = current->next; current->next = previous; previous = current; current = next; } head->next = nullptr; return previous; }
结果也是 8ms 啊,令人失望。
时间: 2024-10-14 04:01:40