劍指offer-----從頭到尾打印鏈表

輸入一個鏈表,按鏈表從尾到頭的順序返回一個ArrayList

/**
*  struct ListNode {
*        int val;
*        struct ListNode *next;
*        ListNode(int x) :
*              val(x), next(NULL) {
*        }
*  };
*/
class Solution {
public:
    vector<int> printListFromTailToHead(ListNode* head) {
        vector<int>res;
        if(head==NULL)
            return res;
        ListNode *p=head;
        while(p!=nullptr)
        {
            res.push_back(p->val);
            p=p->next;
        }
        //reverse(res.begin(),res.end());//直接輸出res,就好,不用再建一個向量
        vector<int>out;
        for(auto iter=res.rbegin();iter!=res.rend();iter++)
        {
            out.push_back(*iter);
        }
        return out;
    }
};

 

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