剑指 Offer 06. 从尾到头打印链表(C++)
题目
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例 1:
输入:head = [1,3,2]
输出:[2,3,1]
限制:
0 <= 链表长度 <= 10000
分析与题解
题解一
主要是使用reverse
函数,reverse函数功能是逆序或反转,多用于字符串、数组、容器。
头文件是#include
,与max_element相同
通过下列示例解释其功能:
string str="hello world , hi";
reverse(str.begin(),str.end());
//str结果为 ih , dlrow olleh
vector<int> v = {5,4,3,2,1};
reverse(v.begin(),v.end());
//容器v的值变为1,2,3,4,5
reverse
函数用于反转在[first,last)范围内的顺序,reverse
函数无返回值
因此对于本体,我们先用vector数组将遍历树的值依次存入,再使用reverse
函数的特型将数组中的元素进行反转。代码如下:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
vector<int> reversePrint(ListNode* head) {
vector<int> res;
ListNode *tmp = head;
while(tmp!=nullptr){
res.push_back(tmp->val);
tmp = tmp->next;
}
reverse(res.begin(),res.end());
return res;
}
};
题解二
因为题目要求倒叙输出所有的元素,因此联想到栈的特性。但因为最后输出是以格式要求的,最后对数据格式进行一个转化。代码如下:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
vector<int> reversePrint(ListNode* head) {
stack<int> res;
vector<int> result;
ListNode *tmp = head;
while(tmp!=nullptr){
res.push(tmp->val);
tmp = tmp->next;
}
while(!res.empty()){
result.push_back(res.top());
//不要忘记从栈中拿出填入数组中的元素
res.pop();
}
return result;
}
};