剑指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
原文地址:https://www.cnblogs.com/alan-W/p/14224590.html