题目描述
输入一个链表,从尾到头打印链表每个节点的值。
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> ans;
dfs(ans, head);
return ans;
}
//递归利用系统栈反向输出,也可以直接使用栈
void dfs(vector<int> &ans, ListNode* head)
{
if(head == nullptr)
return;
dfs(ans, head->next);
ans.push_back(head->val);
}
};