输入一个链表的头节点,按链表从尾到头的顺序返回每个节点的值(用数组返回)。
思路:递归的方法,时间、空间复杂度都是O(n)
实现代码:
#include <vector>
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(NULL) {}
};
void reverseList(ListNode* head, vector<int>& res) {
if (head == NULL) {
return;
}
reverseList(head->next, res);
res.push_back(head->val);
}
vector<int> reversePrint(ListNode* head) {
vector<int> res;
reverseList(head, res);
return res;
}
int main() {
ListNode* head = new ListNode(1);
head->next = new ListNode(2);
head->next->next = new ListNode(3);
head->next->next->next = new ListNode(4);
vector<int> res = reversePrint(head);
for (int i = 0; i < res.size(); i++) {
std::cout << res[i] << " ";
}
std::cout << std::endl;
return 0;
}