zoukankan      html  css  js  c++  java
  • 剑指offer JZ-3

    题目描述

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

    输入

    {67,0,24,58}

    返回值

    [58,24,0,67]

    思路:

    1.递归的特性使得递归可以解决大部分的倒叙输出问题,所以最原始的思路就是直接递归。

    /**
    *  struct ListNode {
    *        int val;
    *        struct ListNode *next;
    *        ListNode(int x) :
    *              val(x), next(NULL) {
    *        }
    *  };
    */
    class Solution {
    public:
        vector<int> printListFromTailToHead(ListNode* head) {
            vector<int> val;
            if(head != NULL)
            {
                vector<int>s = printListFromTailToHead(head->next);
            
                for(int i=0;i<s.size();i++)
                    val.push_back(s[i]);
                val.push_back(head->val);
            }
            return val;
        }
    };
    View Code

    2.使用vector.insert()函数,在遍历时,将当前遍历到的val值 插入到vector的头部。

    /**
    *  struct ListNode {
    *        int val;
    *        struct ListNode *next;
    *        ListNode(int x) :
    *              val(x), next(NULL) {
    *        }
    *  };
    */
    class Solution {
    public:
        vector<int> printListFromTailToHead(ListNode* head) {
            vector<int> val;
            while(head != NULL)
            {
                val.insert(val.begin(), head->val);
                head = head->next;
            }
            return val;
        }
    };
    View Code
  • 相关阅读:
    Hibernate框架—简介
    ooad单例模式-Singleton
    About-JavaOOAD
    win10内置ubuntu,mysql完美清理,并安装
    VUE关于对象动态添加属性无法双向绑定问题
    正则留档
    centos下tomcat中文路径不识别
    web服务器解释html-include
    rose
    聊天框突出箭头
  • 原文地址:https://www.cnblogs.com/alan-W/p/14224590.html
Copyright © 2011-2022 走看看