题目描述
输入一个链表,按链表从尾到头的顺序返回一个ArrayList。

分析
1、首先就想到逆置链表,然后遍历(不过这样好像会改变整个链表):

class Solution
{
public:
vector<int> printListFromTailToHead(ListNode* head)
{
ListNode *cur = head;
ListNode *pre = nullptr;
ListNode *temp = nullptr;
while (cur)
{
temp = cur->next;
cur->next = pre;
pre = cur;
cur = temp;
}

vector<int> result;
while (pre) // 正向输出
{
result.push_back(pre->val);
pre = pre->next;
}
return result;
}
};

2、还有利用stl提供的reverse函数反转:

class Solution
{
public:
vector<int> printListFromTailToHead(ListNode* head)
{
vector<int> result;
while (head) // 正向输出
{
result.push_back(head->val);
head = head->next;
}
std::reverse(result.begin(), result.end()); // 反转
return result;
}
};