题解 | #从尾到头打印链表#
从尾到头打印链表
https://www.nowcoder.com/practice/d0267f7f55b3412ba93bd35cfa8e8035
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
void recursion(ListNode* head, vector<int>& res){
if (head != 0) {
recursion(head->next, res);
res.push_back(head->val);
}
}
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> res;
recursion(head,res);
return res;
}
};
因为是要逆序写入到数组中,链表只能顺序读取节点,因此考虑栈先进后出的性质,通过递归实现。
注意递归函数的形式参数需用vector<int>& res来保证res值可以更改,而vector<int> res意味着函数会创建一个副本,而不会改变输入的实参。

