Sword se refiere a Oferta ------ Imprima la lista enlazada de principio a fin

Inserte la descripción de la imagen aquí

Enlace de tema!

Idea: Esta
pregunta es muy simple, puede usar dfs para hacerlo, o puede voltear la lista vinculada y hacerlo más tarde, solo mire el código.

Código:

/**
 * 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;
    }
};

Supongo que te gusta

Origin blog.csdn.net/weixin_43743711/article/details/114523207
Recomendado
Clasificación