从尾到头打印链表

【问题】输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。

【思路】看到这个题目,一般都可以想到堆栈结构,遍历所有节点压入栈中,然后在依次弹出即可,但这样就会使用额外空间,效率不高!另一种方法是使用DFS(深度优先)的方法,并利用递归来实现,递归终止条件为p的next为NULL就终止。

/**
*  struct ListNode {
*        int val;
*        struct ListNode *next;
*        ListNode(int x) :
*              val(x), next(NULL) {
*        }
*  };
*/
class Solution {
public:
    vector<int> res;    //注意将vector放置全局变量
    vector<int> printListFromTailToHead(ListNode* head) {

        ListNode *p=nullptr;
        p=head;
        if(p!=NULL){
            if(p->next!=nullptr){
                printListFromTailToHead(p->next);
            }
            res.push_back(p->val);
        }
        return res;
    }
};
原文地址:https://www.cnblogs.com/zhudingtop/p/11291277.html