cherrychenlee

导航

 

原文地址:https://www.jianshu.com/p/71189056556d

时间限制:1秒 空间限制:32768K

题目描述

输入一个链表,按链表值从尾到头的顺序返回一个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==nullptr) return res;
        while(head){
            res.push_back(head->val);
            head=head->next;
        }
        reverse(res.begin(),res.end());
        return res;
    }
};

运行时间:3ms
占用内存:476k

/**
*  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==nullptr) return res;
        res.insert(res.begin(),head->val);
        if(head->next){
            vector<int> tmp=printListFromTailToHead(head->next);
            res.insert(res.begin(),tmp.begin(),tmp.end());
        }
        return res;
    }
};

运行时间:4ms
占用内存:484k

posted on 2019-04-27 22:37  cherrychenlee  阅读(64)  评论(0编辑  收藏  举报