力扣 剑指 Offer 06. 从尾到头打印链表 链表 递归

https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof/
力扣 剑指 Offer 06. 从尾到头打印链表 链表 递归_第1张图片

思路一:顺序存储后反向一下再返回即可。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    vector<int> reversePrint(ListNode* head) {
        vector<int> vec;
        while(head)
            vec.push_back(head->val),head=head->next;
        reverse(vec.begin(),vec.end());
        return vec;
    }
};

思路二:利用递归(用栈也可以)。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    void dfs(vector<int> &vec,ListNode* head){
        if(head){
            dfs(vec,head->next);
            vec.push_back(head->val);
        }
    }

    vector<int> reversePrint(ListNode* head) {
        vector<int> vec;
        dfs(vec,head);
        return vec;
    }
};

你可能感兴趣的:(力扣,链表,递归)