题解 | #从尾到头打印链表#
从尾到头打印链表
https://www.nowcoder.com/practice/d0267f7f55b3412ba93bd35cfa8e8035
#include <algorithm> #include <iterator> #include <vector> class Solution { public: vector<int> printListFromTailToHead(ListNode* head) { vector<int>temp; if(head==nullptr) return {}; ListNode* current=head; int length=0; while(current!=nullptr) { temp.push_back(current->val); length++; current=current->next; } //用这种做法,仅用了4字节的数据,就避免了在copy时反复给result数组扩容。 vector<int>result(length); // std::reverse_copy(temp.begin(), temp.end(), std::back_inserter(result)); std::reverse_copy(temp.begin(),temp.end(),result.begin()); return result; } };