码迷,mamicode.com
首页 > 其他好文 > 详细

剑指offer-从尾到头打印链表

时间:2019-02-01 01:17:52      阅读:160      评论:0      收藏:0      [点我收藏+]

标签:实现   nod   next   back   nullptr   ptr   cto   node   push   

题目要求

输入一个链表,从尾到头放入ArrayList并返回。

C++实现

/**
*  struct ListNode {
*        int val;
*        struct ListNode *next;
*        ListNode(int x) :
*              val(x), next(NULL) {
*        }
*  };
*/
class Solution {
public:
    vector<int> printListFromTailToHead(ListNode* head) {
        int length=0;
        ListNode *p=head;
        vector<int> ArrayList;
        while(p!=nullptr){
            ArrayList.push_back(p->val);
            p=p->next;
            length++;
        }
        reverse(ArrayList.begin(),ArrayList.end());
        return ArrayList;
    }
};

头插vector效率很低,所以采用先push_back,后翻转vector的方式。

剑指offer-从尾到头打印链表

标签:实现   nod   next   back   nullptr   ptr   cto   node   push   

原文地址:https://www.cnblogs.com/MarkKobs-blog/p/10344500.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!