当前位置:网站首页>剑指 Offer 06. 从尾到头打印链表
剑指 Offer 06. 从尾到头打印链表
2022-06-10 15:24:00 【soO_007】
题目:
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例 1:
输入:head = [1,3,2]
输出:[2,3,1]
限制:
0 <= 链表长度 <= 10000
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路:
最近比较闲,寻思再走一遍剑指。这题是个简单题,一般人想法就是遍历一遍list存入vector,再reverse vector;或者就地reverse list,再存入vector;再或者存入stack再pop出来,这些其实差别都不大。写了最简单的一版即代码1。之后在看别人的答案时,看到了一版厉害的递归,放到代码2了。确实这题在数据量不大的情况下递归很清楚,不过一般不太会想到。这里base case就是head为空,直接返回一个空的vector,然后我们每次获得的vector都是下一层递归返回的,因为要倒序,我们在下一层返回以后再将当前层的val放进vector的末端,这样就返回的vector就是倒序了。
代码1:
/**
* 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> record;
while (head) {
record.push_back(head->val);
head = head->next;
}
reverse(record.begin(), record.end());
return record;
}
};
代码2:
边栏推荐
- [cloud native | kubernetes] in depth RC, RS, daemonset, statefulset (VII)
- Digital management medium + low code, jnpf opens a new engine for enterprise digital transformation
- 一款完整的多用户微信公众平台开发源码,带文档免费分享
- 点击解锁广和通5G模组“关键词”
- 自媒体视频热门思路分享
- Development of stm8s103f single chip microcomputer (1) lighting of LED lamp
- opencv#4 手写体识别:自建训练集完美
- CVPR 2022 oral | SCI: fast, flexible and robust low light image enhancement
- 如何构建以客户为中心的产品蓝图:来自首席技术官的建议
- 产品设计软件Figma用不了,国内有哪些相似功能的软件
猜你喜欢

视觉SLAM常见的QR分解SVD分解等矩阵分解方式求解满秩和亏秩最小二乘问题(最全的方法分析总结)

广和通高算力智能模组为万亿级市场5G C-V2X注智

In what scenario can we not use the arrow function?

opencv#4 手写体识别:自建训练集完美

3. Encounter the form of handycontrol again

Applet network request promise

推荐一个好用的设计师导航网址

ORB_ Slam2 visual inertial tight coupling positioning technology route and code explanation 3 - tight coupling optimization model

探索数据可视化开发平台FlyFish开源背后的秘密!

How to improve document management
随机推荐
Summary of 5 years' experience in ERP odoo privilege management system setup
Wechat applet slides to the top
Yuntu says that every successful business system cannot be separated from apig
推荐一个好用的设计师导航网址
Mitm (man in the middle attack)
百度开源ICE-BA安装运行总结
Even some people say that ArrayList is twice as large. Today, I will take you to tear up the ArrayList source code
Odoo authority management (access authority and record rules) is applied to upgrade role management
自动化运维必备的工具-Shell脚本介绍
ORB_SLAM2视觉惯性紧耦合定位技术路线与代码详解3——紧耦合优化模型
terminator如何设置字体显示不同颜色
2022 the 14th Nanjing International artificial intelligence product exhibition
小程序警告:Now you can provide attr `wx:key` for a `wx:for` to improve performance.
点投影到平面上的方法总结
Quelqu'un a même dit que ArrayList était deux fois plus grand. Aujourd'hui, je vais vous montrer le code source ArrayList.
数据库创建触发器的问题
Fast detection of short text repetition rate
如何构建以客户为中心的产品蓝图:来自首席技术官的建议
QT 基于QScrollArea的界面嵌套移动
ORB_ Slam2 visual inertial tight coupling positioning technology route and code explanation 2 - IMU initialization