首页 > 其他 > 详细

从尾到头打印链表

时间:2018-08-18 12:21:50      阅读:161      评论:0      收藏:0      [点我收藏+]

题目描述

输入一个链表,按链表值从尾到头的顺序返回一个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;
    }
};

 

 

从尾到头打印链表

原文:https://www.cnblogs.com/dreamstick/p/9496548.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!