题目描述
以数组的形式返回倒序的链表
题目链接
思路:这题标着简单,就直接简单点,遍历链表,存到vector里,再利用stl里面的反转函数,即可
代码:
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int>ans;
while(head)
{
ans.push_back(head->val);
head=head->next;
}
reverse(ans.begin(),ans.end());
return ans;
}
};思路2(递归)
这题可以用递归处理,递归的代码十分的简洁,为什么可以递归呢,因为当前遍历到的数要放到最后,那么可以先递归出来后面的在把当前的数加进去,非常完美的解决了倒序的问题,下面给出代码
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int>ans;
//记录答案
if(head==nullptr)return ans;
//链表为空则返回空数组
ans=printListFromTailToHead(head->next);
//递归得到答案
ans.push_back(head->val);
加入最后一个数
return ans;
}
};
京公网安备 11010502036488号