• 从尾到头打印链表


    题目描述

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

    法一:非递归

    /**
    *  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;
            while(head){
                ans.push_back(head -> val);
                head = head -> next;
            }
            reverse(ans.begin(), ans.end());
            return ans;
        }
    };
    

    法二:非递归

    /**
    *  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;
            while(head){
                ans.insert(ans.begin(), head -> val);
                head = head -> next;
            }
            return ans;
        }
    };
    

    法三:递归

    /**
    *  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 != NULL){
                ans = printListFromTailToHead(head -> next);
                ans.push_back(head -> val);
            }
            return ans;
        }
    };
    

      

  • 相关阅读:
    Win8常用快捷键
    清除远程桌面连接记录
    通过注册表改变“我的文档”等的默认位置,防止系统重装造成数据丢失
    HTML 转义字符对照表
    r语言 函数
    sparkr——报错
    R语言--saprkR基本使用
    r绘图基本
    R绘制中国地图,并展示流行病学数据
    r画饼图
  • 原文地址:https://www.cnblogs.com/tyty-Somnuspoppy/p/12274973.html
Copyright © 2020-2023  润新知