链表逆序打印

输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    void SaveNode(ListNode* head, std::vector<int>& list) {
        if (head != NULL) {
            SaveNode(head->next, list);
            list.push_back(head->val);
        }
        return;
    }
    vector<int> reversePrint(ListNode* head) {
        std::vector<int> res;
        SaveNode(head, res);
        return res;
    }
};

 

posted @ 2021-03-06 23:13  HuLargeSun  阅读(47)  评论(0)    收藏  举报