输入一个链表,按链表值从尾到头的顺序返回一个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> ret;
if (head == NULL) return ret;
//反转链表
ListNode d(-1);
ListNode* dummy = &d;
for (;head != NULL;) {
ListNode* tmp = head->next;
head->next = dummy->next;
dummy->next = head;
head = tmp;
}
for (;dummy->next != NULL;) {
ret.push_back(dummy->next->val);
dummy = dummy->next;
}
return ret;
}
};