输入一个链表,按链表从尾到头的顺序返回一个ArrayList。
这个题想到用STL中的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> v;
while(head!=NULL)
{
v.push_back(head->val);//从尾部将链表元素放入vector中
head=head->next;
}
reverse(v.begin(),v.end());//c++标准库文件 逆转开始到结尾的元素
return v;
}
};