链接:https://www.nowcoder.com/questionTerminal/d0267f7f55b3412ba93bd35cfa8e8035
输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。
测试用例:
输入:[1,2,3]
输出:[3,2,1]
先将链表中的数据存入vector类对象中,然后用反向迭代器将对象内容翻转即可。
C++解法
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> res;
vector<int> printListFromTailToHead(ListNode* head) {
while(head != NULL){
res.push_back(head->val);
head = head->next;
}
res = vector<int>(res.rbegin(),res.rend());
return res;
}
};













网友评论