描述
输入一个链表的头节点,按链表从尾到头的顺序返回每个节点的值(用数组返回)。
如输入{1,2,3}的链表如下图:
![](https://img-blog.csdnimg.cn/img_convert/85d73454fdc3dc734f5052532e07c184.png)
返回一个数组为[3,2,1]
0 <= 链表长度 <= 10000
示例1
输入:
{1,2,3}
返回值:
[3,2,1]
示例2
输入:
{67,0,24,58}
返回值:
[58,24,0,
思路:
将整个链表放进res数组中,然后reverse函数进行反转,返回res即可。
题解:
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> res;
while (head) {
res.push_back(head->val);
head = head->next;
}
//直接反转
reverse(res.begin(), res.end());
return res;
}
};