从尾到头打印链表

 

输入一个链表,按链表从尾到头的顺序返回一个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> vec;
        ListNode *p = head;
        vec = next(p, vec);
        return vec;
    }
    
    vector<int> next(ListNode *p, vector<int> vec){
        if(p != NULL){
            vec = next(p->next,vec);
            vec.push_back(p->val);
        }
        return vec;
    }
};

 

posted @ 2020-03-10 20:48  jenningszheng  阅读(96)  评论(0编辑  收藏  举报