Sword refers to Offer------Print the linked list from end to beginning

Insert picture description here

Topic link!

Idea: This
question is very simple, you can use dfs to do it, or you can flip the linked list and do it later, just look at the code.

Code:

/**
 * 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>& ans,ListNode* head){
    
    
        if(head==NULL) return ;
        dfs(ans,head->next);
        ans.push_back(head->val);
        return ;
    }
    vector<int> reversePrint(ListNode* head) {
    
    
        vector<int> ans;
        dfs(ans,head);
        return ans;
    }
};

Guess you like

Origin blog.csdn.net/weixin_43743711/article/details/114523207