题目:输入一个链表,按链表值从尾到头的顺序返回一个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> vec1,vec2;
ListNode* p = head;
while(p != NULL){
vec1.push_back(p->val); //遍历链表,将链表中的值,全部顺序存入vec1
p = p->next;
}
int capacity = vec1.size();
int k = 0;
for(int i = capacity-1; i >= 0 ; i--)
vec2.push_back(vec1[i]); //反向输出.这里用了额外空间,可以优化.
return vec2;
}
};
一刷都是最容易想到的办法,二刷再来优化