剑指 Offer 06. 从尾到头打印链表

LeetCode题目:递归

输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。

示例 1:

输入:head = [1,3,2]
输出:[2,3,1]

限制:

0 <= 链表长度 <= 10000

初始代码

/**
 * 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) {

    }
};

解题思路

又是链表的递归

这题拿来入门链表的递归题还是不错的。递归的“递”操作结束后栈顶元素为链表尾节点的相关操作。那么直接递归到尾节点保存其值即可。那么递归中”递“的操作应该一直到尾节点的下一个节点,即head=NULL时结束。不然会跳过尾节点。

完整代码

/**
 * 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>nums;
        if(head==NULL)
            return nums;
        nums=reversePrint(head->next);
        nums.push_back(head->val);
        return nums;
    }
};
Subscribe
提醒
0 评论
Inline Feedbacks
View all comments
0
在此留下你的评论x