算法1 数组reverse
定义一个vector数组,将链表遍历一遍目的是将链表中的val放到数组中,最后将数组反转
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
vector<int> printListReversingly(ListNode* head) {
vector<int> res;
while(head){
res.push_back(head->val);
head=head->next;
}
reverse(res.begin(),res.end());
return res;
}
};
算法2 非尾部递归
递归有两种形式,第一种是尾递归,第二种叫非尾部递归。
通俗来讲,尾递归是正序的,将输出语句放在递归语句的前面;而非尾部递归是逆序的,把输出语句放到递归语句的后面。
再来分析一下这道题,“从尾到头”很明显是逆序的,所以使用非尾部递归。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
vector<int> printListReversingly(ListNode* head) {
vector<int> res;
while(head){
res.push_back(head->val);
head=head->next;
}
reverse(res.begin(),res.end());
return res;
}
};