从尾到头打印链表

时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M

题目描述

输入一个链表,按链表从尾到头的顺序返回一个ArrayList。
 
思路一:从头遍历链表中的元素,并以此存入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> saveElem ;
        while(head)
        {
            saveElem.push_back(head->val);
            head = head->next;
        }
        reverse(saveElem.begin(),saveElem.end());
        return saveElem;
    }
};
思路二:采用递归的操作,递归访问元素,并采用头插法的方式进行储存
/**
*  struct ListNode {
*        int val;
*        struct ListNode *next;
*        ListNode(int x) :
*              val(x), next(NULL) {
*        }
*  };
*/
class Solution {
public:
    vector<int> printListFromTailToHead(ListNode* head) {
        vector<int> saveElem;
        if(head)
        {
            saveElem.insert(saveElem.begin(),head->val);
            if(head->next)
            {
                vector<int> tempVec = printListFromTailToHead(head->next); 
                if(tempVec.size())
                {
                    saveElem.insert(saveElem.begin(),tempVec.begin(),tempVec.end());  
                }
            }
        }
        return saveElem;
    }
};
此时,我产生了一个疑问,每次递归都将元素采用头插法的方式存入saveElem中,最后saveElem的就是以倒序的形式存在。

 做一个简图,根据上面的程序,应该是这样的,当head->next为空,也就是到了第5步,此时,产生一个返回值,但由于递归调用中每一层变量相互独立的关系,需要将saveElem重新存入第一次调用时的那层的saveElem,因此出现了这条语句

if(tempVec.size())
{
    saveElem.insert(saveElem.begin(),tempVec.begin(),tempVec.end());  
}

递归调用中使用全局变量和函数参数之间的差异(参考:https://blog.csdn.net/wuwei35531/article/details/84424238)

存在一些参数,可以用
1. 全局变量表示,递归结束后必须对该变量修改,恢复原值
2. 普通函数参数,因为递归调用函数时,实际上,从内存分布上看,每一层调用都保存了该层函数的参数,因此递归返回上层时,不会影响原参数值

原文地址:https://www.cnblogs.com/whiteBear/p/12392697.html