6.从尾到头打印链表
题目描述
输入一个链表,从尾到头打印链表每个节点的值。
题目很经典,因此本文用三种方法来处理。(严格来说算2种)
思路1
先顺序输出链表数据,然后翻转输出的结果。
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
if (head == NULL) return {};
vector<int> ret;
ListNode* pRead = head;
while(pRead != NULL) {
ret.push_back(pRead->val);
pRead = pRead->next;
}
std::reverse(ret.begin(), ret.end());
return ret;
}
};
从头到位遍历一遍数据,因此时间复杂度:O(n)
空间复杂度:O(n)
思路2 栈 非递归
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
if (head == NULL) return {};
std::stack<ListNode*> sk;
ListNode* pRead = head;
while (pRead != NULL) {
sk.push(pRead);
pRead = pRead->next;
}
vector<int> ret;
while (!sk.empty()) {
ret.push_back(sk.top()->val);
sk.pop();
}
return ret;
}
};
思路3 栈 递归
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
if (head == NULL) return {};
vector<int> ret;
ListNode* pRead = head;
help(ret, pRead);
return ret;
}
void help(vector<int>& ret, ListNode* node) {
if (node == NULL) return;
help(ret, node->next);
ret.push_back(node->val);
}
};