題目描述
輸入一個鏈表,按鏈表從尾到頭的順序返回一個ArrayList。
思路:這裏我直接想到的是vector存入後直接反轉,後來看到他人答案利用遞歸做也很巧妙。
方法一:直接反轉
/**
* 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;
ListNode* pHead = NULL;
pHead = head;
while(pHead)
{
ans.push_back(pHead->val);
pHead = pHead->next;
}
reverse(ans.begin(),ans.end());
return ans;
}
};
方法二:利用遞歸存儲
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
ListNode* pHead = NULL;
pHead = head;
if(pHead)
{
printListFromTailToHead(pHead->next);
ans.push_back(pHead->val);
}
return ans;
}
private:
vector<int>ans;
};