1.题目:
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
2.示例 :
输入:head = [1,3,2]
输出:[2,3,1]
3.思路:先遍历链表将链表中的数放入数组ret中,再利用reverse()函数使数组变为倒叙,最后返回ret.
4.代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
vector<int> reversePrint(ListNode* head) {
vector<int> ret;
while(head)
{
ret.push_back(head->val);
head=head->next;
}
reverse(ret.begin(),ret.end());
return ret;
}
};