题目描述
输入一个链表,按链表从尾到头的顺序返回一个ArrayList。
解题思路:
链表元素存入vector中,再使用reverse反转。
代码实现:
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> result;
//链表元素存入vector中
while(head!= NULL){
result.push_back(head->val);
head = head->next;
}
//反转vector
reverse(result.begin(),result.end());
return result;
}
};