0. 题目链接
1. 问题描述
2. 运行示例
3. 解题思路
3.1 方法一
思路一:使用栈Stack,将链表的元素先依次入栈,利用栈的先进后出,将数据依次出栈后存放到对应数组中,则为链表的倒序。
代码实现:
vector<int> printListFromTailToHead(ListNode* head) {
stack<int> s;
ListNode* p = head;
while(p){ // 当p指针不为null时
s.push(p->val); // 将链表元素依次入栈
p = p->next; // 指向下一结点
}
vector<int> ans; // 结果数组
while(!s.empty()){ // 当栈不为空时
ans.push_back(s.top()); // 依次将栈顶元素push到vector中
s.pop(); // 移除栈顶元素
}
return ans;
}
3.2 方法二
思路二:将链表数据依次存放到数组容器vector中,返回它的倒序结果。
代码实现:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> v;
ListNode* p = head;
while(p){
v.push_back(p->val);
p = p->next;
}
return vector<int> (v.rbegin(),v.rend());
}
3.3 方法三
思路三:利用递归函数,将链表元素从后向前依次存到结果数组中。
代码实现:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> ans;
ListNode*p = head;
reves(p,ans);
return ans;
}
void reves(ListNode*p,vector<int> &ans){
if(p){ // 如果p不为null
if(p->next) // 如果p->next不为null
reves(p->next,ans); // 向下递归
ans.push_back(p->val); // 存放结果
}
}
——————END-2022-05-01——————