当前位置:网站首页>剑指 Offer 06. 从尾到头打印链表
剑指 Offer 06. 从尾到头打印链表
2022-06-22 20:52:00 【前端粉刷匠】
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
例子:
输入:head = [1,3,2]
输出:[2,3,1]
解法1:
思路:将head数组变成一个链表,然后将链表的头输入。每次将第一个插入到数组的第一个最前面。考察的知识点就是链表的逆置,突破点在与先找到最后一个节点,然后从倒数第二个开始逆转。
let head = [1,3,2]
// 创建链表
function ListNode(val){
this.val = val;
this.next = null;
}
let a = new ListNode();
let b = new ListNode();
let c = new ListNode();
a.val = head[0];
a.next = b;
b.val = head[1];
b.next = c;
c.val = head[2];
c.next = null;
// 反转数组
function reversePrint(head){
let arr = []
while(head != null){
arr.unshift(head.val)
head = head.next;
}
return arr;
}
解法2:
思路:将链表中的数据保存到数组中,然后使用数组的reverse()方法逆转
function reversePrint(head){
let arr = []
while(head != null){
arr.push(head.val)
head = head.next;
}
return arr.reverse();
}
暂时想多这么多~ 如果大家还有好方法,欢迎推荐~~
七夕快乐~~
边栏推荐
- 2021-04-16
- Reinforcement learning weekly (issue 50): saferl kit, gmi-drl, rp-sdrl & offline meta reinforcement learning
- node-fetch下载文件
- A spark app demo
- C language -- 17 function introduction
- How much do you know about the cause of amplifier distortion?
- Solution to cache inconsistency
- 2020-12-20
- R language data Table data import practice: data Rename the name of the table data column (rename)
- 一个spark app demo
猜你喜欢

2021-04-16

Dragon City in Europe | National Geographic the most romantic and safe destination in the world

leetcode. 11 --- container with the most water

Do domestic mobile phones turn apples? It turned out that it was realized by 100 yuan machine and sharp price reduction

mysql主从同步及其分库分表基本流程

Technology cloud report: East to West computing is not only about "computing", but also needs "new storage"

2021-04-14

The breakthrough of key chips hindering Huawei 5g mobile phones has been achieved, and domestic chips have gained 10% share

Spark RDD Programming Guide(2.4.3)

Explain the startup process of opengauss multithreading architecture in detail
随机推荐
Help customers' digital transformation and build a new operation and maintenance system
2020-12-20
Introduction and example application of PostgreSQL string separator function (regexp\u split\u to\u table)
Fundamentals of shell programming (Part 7: branch statement -if)
c# sqlsugar,hisql,freesql orm框架全方位性能测试对比 sqlserver 性能测试
Lua -- iterator, module, meta table
2021-04-16
Zynq ultrascale + rfsoc zcu111 RF clock tree learning 1
Several ways of redis persistence -- deeply parsing RDB
【22暑期复建1】 Codeforces Round #791 (Div. 2)
three.js模拟驾驶游览艺术展厅---打造超级相机控制器
Greedy interval problem (2)
Reinforcement learning weekly (issue 50): saferl kit, gmi-drl, rp-sdrl & offline meta reinforcement learning
对 cookie 的添加/获取和删除
2020-12-20
js----SVG转PNG
2021-04-16
Basic MySQL database operations
MySQL multi table operation
2021-04-14