从尾到头打印链表

题目描述

输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。
方法1:利用递归
class Solution {
public:
    vector<int> printListFromTailToHead(ListNode* head) {
        vector<int> res;
        printListFromTailToHead(res,head);
        return res;
        
    }
    void printListFromTailToHead(vector<int>& res,ListNode* node)
    {
        if(node!=NULL)
        {
           printListFromTailToHead(res,node->next); 
           res.push_back(node->val);
        }
    }
};

 

方法2:利用栈
class Solution {
public:
    vector<int> printListFromTailToHead(ListNode* head) {
        
        vector<int> res;
        stack<int> stk;
        int value;
        ListNode* p = head;
        while(p!=NULL)
        {
            stk.push(p->val);
            p = p->next;
        }
        while(!stk.empty())
        {
            value = stk.top();
            stk.pop();
            res.push_back(value);
        }
        return res;
    }
};

 

方法3:利用stl中algorithm库的反转函数reverse
class Solution {
public:
    vector<int> printListFromTailToHead(ListNode* head) {
        
        vector<int> res;
        ListNode* p = head;
        while(p!=NULL)
        {
            res.push_back(p->val);
            p = p->next;
        }
        reverse(res.begin(),res.end());
        return res;
    }
};

 

 
posted @ 2018-08-18 11:06  wym95  阅读(111)  评论(0)    收藏  举报