简单:
从尾到头打印链表 |
题目描述
输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
//???!?!?!?!
int n=0;
auto p=head;
vector<int>vec;
while(p!=NULL)
{
n++;
p=p->next;
}
// vec.reserve(n+1); //有毒吧
vec.resize(n);
while(head!=NULL)
{
vec[--n]=head->val;
head=head->next; // oh my god !!!
}
return vec;
}
};