题解 | #从尾到头打印链表#

从尾到头打印链表

http://www.nowcoder.com/questionTerminal/d0267f7f55b3412ba93bd35cfa8e8035

题目描述
以数组的形式返回倒序的链表
题目链接
思路:这题标着简单,就直接简单点,遍历链表,存到vector里,再利用stl里面的反转函数,即可
代码:

class Solution {
public:
    vector<int> printListFromTailToHead(ListNode* head) {
        vector<int>ans;
        while(head)
        {
            ans.push_back(head->val);
            head=head->next;
        }
        reverse(ans.begin(),ans.end());
        return ans;
    }
};

思路2(递归)
这题可以用递归处理,递归的代码十分的简洁,为什么可以递归呢,因为当前遍历到的数要放到最后,那么可以先递归出来后面的在把当前的数加进去,非常完美的解决了倒序的问题,下面给出代码
图片说明

/**
*  struct ListNode {
*        int val;
*        struct ListNode *next;
*        ListNode(int x) :
*              val(x), next(NULL) {
*        }
*  };
*/
class Solution {
public:
    vector<int> printListFromTailToHead(ListNode* head) {
        vector<int>ans;
            //记录答案
        if(head==nullptr)return ans;
            //链表为空则返回空数组
        ans=printListFromTailToHead(head->next);
            //递归得到答案
        ans.push_back(head->val);
            加入最后一个数
        return ans;
    }
};
全部评论

相关推荐

刘湘_passion:太强了牛肉哥有被激励到
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务