1 题目描述
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
2 思路
栈、递归、reverse
3 代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
vector<int> res;
vector<int> reversePrint(ListNode* head) {
//reverse
/*
while(head) {
res.push_back(head->val);
head = head->next;
}
//使用algorithm算法中的reverse反转res
reverse(res.begin(), res.end());
return res;
*/
//栈
/*
stack<int> s;
//入栈
while(head) {
s.push(head->val);
head = head->next;
}
//出栈
while(!s.empty()) {
res.push_back(s.top());
s.pop();
}
return res;
*/
//递归
if(head == nullptr) {
return res;
}
reversePrint(head->next);
res.push_back(head->val);
return res;
}
};