题目描述:
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例 1:
输入:head = [1,3,2]
输出:[2,3,1]
限制:0 <= 链表长度 <= 10000
这是一道对单链表遍历的入门算法题。但是,我将运用三种方法来解决此题。从而达到学一题等于学三题的目的。
方法一:使用std::reverse()函数
看到题目的第一反应,无非是将单链表遍历一下,将每一个结果存入数组中,最后再翻转一下数组即可
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> ret;
while(head){
ret.push_back(head->val);
head = head->next;
}
std::reverse(ret.begin(), ret.end());
return ret;
}
};
方法二:递归版本
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> ret;
if(!head)
return ret;
ret = printListFromTailToHead(head->next);
ret.push_back(head->val);
return ret;
}
};
方法三:反转链表
首先准备一个pre结点初始指向nullptr,表示正在反转结点的前一个结点,再准备一个cur,表示当前正在反转的结点,cur初始化为head,最后在准备一个temp,表示还未反转的第一个结点。
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
ListNode* pre = nullptr;
ListNode* cur = head;
ListNode* temp = cur;
while(cur){
temp = cur->next;
cur->next = pre;
pre = cur;
cur = temp;
}
vector<int> ret;
while(pre){
ret.push_back(pre->val);
pre = pre->next;
}
return ret;
}
};