当前位置: 首页 > news >正文

【数据结构与算法】力扣 206. 反转链表

题目描述

给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。

示例 1:

输入: head = [1,2,3,4,5]
输出: [5,4,3,2,1]

示例 2:

输入: head = [1,2]
输出: [2,1]

示例 3:

输入: head = []
输出: []

提示:

  • 链表中节点的数目范围是 [0, 5000]
  • -5000 <= Node.val <= 5000

分析解答

先说整体思路:既然要翻转,也就是指针的指向改变。那么就可以让后一个指向自身,自身再指向null。

而且每一个节点都是相同的操作,直接使用递归即可解决。

结束条件是head == null || head.next == null。代码如下:

/*** Definition for singly-linked list.* function ListNode(val, next) {*     this.val = (val===undefined ? 0 : val)*     this.next = (next===undefined ? null : next)* }*/
function ListNode(val, next) {this.val = (val===undefined ? 0 : val)this.next = (next===undefined ? null : next)
}
/*** @param {ListNode} head* @return {ListNode}*/
var reverseList = function(head) {if (head == null || head.next == null) return headlet result = reverseList(head.next)head.next.next = headhead.next = nullreturn result
};

思路拓展

上面使用了递归的操作。下面我们讲讲使用双指针的写法。

image.png

双指针 pre 和 cur,不断移动 pre 和 cur,使得 cur 指向 pre。temp 的作用是防止 cur.next 丢失。

注意要移动 pre,否则 cur 的值会发生改变。

/*** Definition for singly-linked list.* function ListNode(val, next) {*     this.val = (val===undefined ? 0 : val)*     this.next = (next===undefined ? null : next)* }*/
function ListNode(val, next) {this.val = (val===undefined ? 0 : val)this.next = (next===undefined ? null : next)
}
/*** @param {ListNode} head* @return {ListNode}*/
var reverseList = function(head) {let pre = nulllet cur = headwhile (cur) {let temp = cur.nextcur.next = prepre = curcur = temp}return pre
};
http://www.lryc.cn/news/333590.html

相关文章:

  • 【随笔】Git 高级篇 -- 本地栈式提交 rebase | cherry-pick(十七)
  • 数据结构-- 基于顺序表的通讯录代码讲解
  • qt-C++笔记之QLabel加载图片
  • Unity中UI系统1——GUI
  • GIt 删除某个特定commit
  • Django --静态文件
  • 蓝桥杯第十三届省赛C++B组(未完)
  • 编程生活day7--明明的随机数、6翻了、吃火锅
  • css酷炫边框
  • 使用 Docker 部署 Photopea 在线 PS 工具
  • 回溯法(一)——全排列 全组合 子集问题
  • 【Pt】马灯贴图绘制过程 04-玻璃脏迹
  • Rust 程序设计语言学习——枚举模式匹配
  • 正则表达式(1)
  • nginx + keepalived 搭建教程
  • React事件和原生事件的执行顺序
  • 为什么在计算查询Q和键K的矩阵乘法时需要转置键矩阵K。示例说明q11,k11代表什么。线性变换矩阵 W_q 用于生成查询,W_k 用于生成键怎么获取的。
  • 剑指Offer题目笔记27(动态规划单序列问题)
  • 撸代码时,有哪些习惯一定要坚持?
  • 【leetcode面试经典150题】17.罗马数字转整数(C++)
  • 前后端开发之——文章分类管理
  • 第12届蓝桥杯省赛 ---- C/C++ C组
  • IVS模型解释
  • 通用开发技能系列:Git
  • 最新怎么订阅OnlyFans上喜欢的博主,详细教程
  • Mysql故障和优化
  • Windows系统C盘空间优化进阶:磁盘清理与Docker日志管理
  • 14届蓝桥杯 C/C++ B组 T7 子串简写 (字符串)
  • Android 系统大致启动流程
  • 【Web】2024红明谷CTF初赛个人wp(2/4)