劍指offer-鏈表從後往前打印

從尾到頭打印鏈表

題目描述

輸入一個鏈表,從尾到頭打印鏈表每個節點的值。
輸入描述:

輸入爲鏈表的表頭


解法一 : (遞歸)
class Solution {
public:
    vector<int> printListFromTailToHead(struct ListNode* head) {
        vector<int> re;
        if(head==NULL)
        {
            return re;
        }
        if(head->next==NULL )
        {
            re.push_back(head->val);
        }
        else
        {
            re=printListFromTailToHead(head->next);
            re.push_back(head->val);
        }
        return re;

    }
};



解法二:(非遞歸,使用stack來實現)
class Solution {
public:
    vector<int> printListFromTailToHead(struct ListNode* head) {
        stack<int> stk;
        vector<int> re;
        int tempval;
        ListNode *temp;
        temp=head;
        while(temp!=NULL)
            {
            stk.push(temp->val);
            temp=temp->next;
        }
        while(!stk.empty())
        {
            tempval=stk.top();
            stk.pop();
            re.push_back(tempval);
        }
        return re;
    }
};


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