《剑指Offer》06 “从尾到头打印链表”(c++)
①原版(栈)
方法:建栈,基于循环实现(自头到尾push,自尾到头pop)
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
std::stack<ListNode*> nodes;
vector<int> res;
ListNode* pNode = head;
while (pNode != nullptr) {
nodes.push(pNode);
pNode = pNode->next;
}
while (!nodes.empty()) {
pNode = nodes.top();
//printf("%d\t", pNode->val); //打印list
res.push_back(pNode->val); //返回list
nodes.pop();
}
return res;
}
};
② 原版(递归)
递归本质:栈结构
缺点:当链表很长,函数调用层级很深,或导致函数调用栈溢出
错误代码 / 错误结果:
//错误代码,因res未调用在递归内调用,甚至反复初始化
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> res;
if (head != nullptr) {
if (head->next != nullptr) {
printListFromTailToHead(head->next);
}
//printf("%d\t", head->val);
res.push_back(head->val);
}
return res;
}
正确代码(递归调用):
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> res;
TTH_res(head, res); //递归
return res;
}
void TTH_res(ListNode* head, vector<int>& res) {
if (head == nullptr) return;
TTH_res(head->next, res);
res.push_back(head->val);
}
③reverse(arr.begin(), arr.end());
方法:直接利用reverse()函数做翻转
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> res;
while (head != nullptr) {
res.push_back(head->val);
head = head->next;
}
//std::reverse(res.begin(), res.end());
reverse(res.begin(), res.end());
return res;
}