Jianzhi 3. Print linked list from tail to head

Link

topic

insert image description here

train of thought

Traverse it once and put it in the vector, then reverse it

the code

class Solution {
    
    
public:
    vector<int> printListFromTailToHead(ListNode* head) {
    
    
        vector<int> ArratList;
        ListNode *p = head;
        while (p) {
    
    
            ArratList.push_back(p->val);
            p = p->next;
        }
        //reverse(ArratList.begin(), ArratList.end()); //反转函数
        //return ArratList;
        
        return vector<int>(ArratList.rbegin(), ArratList.rend()); //反向迭代
    }
};

Guess you like

Origin blog.csdn.net/weixin_44119881/article/details/112184981