剑指 Offer 06. 从尾到头打印链表

输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。

   示例 1:

    输入:head = [1,3,2]
    输出:[2,3,1]
==================================================================
思路:借助辅助栈,栈的结构是先进后出,正合题意
上代码:
class Solution {
public:
    vector<int> reversePrint(ListNode* head) {
        vector<int> ans;
        stack<int> a;
        while (head) {
            a.push(head->val);
            head = head->next;
        }
        while (!a.empty()) {
            ans.push_back(a.top());
            a.pop();
        }
        return ans;
    }
};

看到官方的解题思路有提到用递归,我也是觉得用辅助栈这个题目过于简单,又写了一版递归的代码

class Solution {
public:
    vector<int> reversePrint(ListNode* head) {
        vector<int> ans;
        recursion(head, ans);
        return ans;
    }
    void recursion(ListNode* head, vector<int> &ans) {
        if (head){
            recursion(head->next, ans);
            ans.push_back(head->val);
        }
    }
};

 

posted on 2022-01-06 21:40  4小旧  阅读(26)  评论(0)    收藏  举报

导航