劍指Offer第三題:從尾到頭打印鏈表

題目描述

輸入一個鏈表,按鏈表從尾到頭的順序返回一個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;
};

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章