描述
输入一个链表的头节点,按链表从尾到头的顺序返回每个节点的值(用数组返回)。
如输入{1,2,3}的链表如下图:
返回一个数组为[3,2,1]
0 <= 链表长度 <= 10000
用一个辅助数组,正向遍历链表加入数组,返回逆置数组
代码:
class Solution {
public:
vector<int>res;
vector<int> printListFromTailToHead(ListNode* head) {
vector<int>res;
ListNode *p=head;
while(p){
res.push_back(p->val);
p=p->next;
}
reverse(res.begin(),res.end());
return res;
}
};