JZ06-从尾到头打印链表

image
image

/**
*  struct ListNode {
*        int val;
*        struct ListNode *next;
*        ListNode(int x) :
*              val(x), next(NULL) {
*        }
*  };
*/
#include <cstddef>
class Solution {
public:
    //输入一个链表的头节点,按链表从头到尾的顺序返回每个节点的值(用数组返回)

    //递归函数  找到链表尾,然后把链表尾的元素存到vector容器中
    //第一个参数是头节点,第二个参数 vector容器,但是要引用访问,因为要存入元素
    void recursion(ListNode * head, vector<int>& res)
    {
        if(head != NULL)
        {
            //递归遍历到尾节点,将为节点元素插入到vector容器中
            recursion(head->next, res);
            res.push_back(head->val);
        }
    }

    //返回值是int类型的vector容器, 函数参数是头指针
    vector<int> printListFromTailToHead(ListNode* head) {
        
        vector<int> res;    //实例化一个vector容器
        recursion(head, res);
        return res;
    }
};

posted @ 2024-04-10 18:58  蓝色的海嗷  阅读(9)  评论(0)    收藏  举报