题目描述
输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。
代码
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution
{
public:
vector<int> printListFromTailToHead(struct ListNode* head)
{
vector<int> v;
while(head != NULL)
{
v.insert(v.begin(), head->val);
head = head->next;
}
return v;
}
};
运行结果
运行时间:5ms
占用内存:476k
解题思路
灵活运用 stl
时间复杂度 O(n),空间复杂度 O(n)