4、从尾到头打印链表
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例 1:
输入:head = [1,3,2]
输出:[2,3,1]
限制:
0 <= 链表长度 <= 10000
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof
思路:
因为题目是返回一个数组,所以我们可以直接顺着遍历并存下来,返回的时候直接用反向迭代器创建一个新数组就好了。(如果没有反向的话其实也很简单,直接新键一个数组,将答案数组从后往前赋值给新建数组)
过程图解:
代码实现:
class Solution {
public:
vector<int> reversePrint(ListNode* head) {
vector<int> res;
while(head)
{
res.push_back(head->val);
head = head->next;
}
return vector<int> (res.rbegin(), res.rend());
}
};