题目描述
输入一个链表,从尾到头打印链表每个节点的值。
思路:巧妙借助递归的思想,利用递归的深度关系从尾到头打印链表中的每个结点的值。
C/C++代码:
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution
{
public:
vector<int> printListFromTailToHead(struct ListNode *head)
{
vector<int> recursion;
if(head != NULL)
{
if(head -> next != NULL)
{
recursion = printListFromTailToHead(head -> next);
}
recursion.push_back(head -> val);
}
return recursion;
}
};