输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。
思路:没什么好说的,利用栈的先进后出,可以实现反转功能。
/**
* 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;
if (head == NULL)
return res;
while(head) {
res.push_back(head->val);
head = head->next;
}
std::reverse(res.begin(),res.end());
return res;
}
};