从尾到头打印链表 ---- newcoder

题目描述:

输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。

newcoder 网页链接


以下为 2019.06.05 更新

/**
*  struct ListNode {
*        int val;
*        struct ListNode *next;
*        ListNode(int x) :
*              val(x), next(NULL) {
*        }
*  };
*/
class Solution {
public:
    vector<int> printListFromTailToHead(ListNode* head) {
        /**
         * 利用 vector 的 insert(vec.begin(), val)方法很简单的就可以完成这个函数
         */
#if 0
        std::vector<int> ret;
        if (!head)
        {
            return ret;
        }
        while(head != nullptr)
        {
            ret.insert(ret.begin(), head->val);
            head = head->next;
        }
        
        return ret;
#endif
        /**
         * 但是很明显,这个题不是考察我们 vector 的操作
         * 所以我们还是老实的用常规思路来解决这个问题
         * 既然要从尾到头打印链表,单链表的话,我们是没有办法从尾再往前走的
         * 所以我们可以考虑递归
         * 我们再定义一个辅助函数来完成这个递归操作吧
         */
#if 0
        std::vector<int> ret;
        assist(ret, head);
        return ret;
#endif
        /** 
         * 既然递归可以解决,我们借助于栈,应该也是可以完成这个功能的
         */
        std::stack<ListNode*> s;
        std::vector<int> ret;
        while(head)
        {
            s.push(head);
            head = head->next;
        }
        // 之后出栈,依次push_back到vector里即可
        while(!s.empty())
        {
            head = s.top();
            s.pop();
            ret.push_back(head->val);
        }
        return ret;
        
    }
private:
    void assist(std::vector<int>& array, ListNode* head)
    {
        // 这是递归出口
        if(head == nullptr)
        {
            return;
        }
        
        assist(array, head->next);
        array.push_back(head->val);
    }
};

以上为 2019.06.05 更新

 

 题解:

链表部分的题目

刚拿到这个题的时候,很奇怪啊,明明是从尾到头打印链表,却偏偏返回了一个 vector

于是就采用循环迭代的方式:

因为 vector 有一个方法叫做指定位置插入(insert()),虽然我是顺序遍历的,但我只要每次插入结点的时候在

开始位置(begin())就可以了。

下面附上代码:

代码已上传 github,可用 git 工具下载查看

gitbub 代码链接,欢迎点击查看

/**
*  struct ListNode {
*        int val;
*        struct ListNode *next;
*        ListNode(int x) :
*              val(x), next(NULL) {
*        }
*  };
*/
class Solution {
public:
    std::vector<int> printListFromTailToHead(ListNode* head)
    {
        std::vector<int> res;
        while(head != nullptr)
        {
            res.insert(res.begin(), head->val);
            head = head->next;
        }

        return res;
    }
};

同志们有问题或者有更好的解决办法,欢迎留言讨论,谢谢大家 :)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值