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

LeetCode 热题100:206. 反转链表

这道简单题,两个简单的思路,链表的思路基本比较类似:使用额外数据结构存储迭代遍历的val、快慢指针等等。

方法一:使用数组存储遍历结果,再反向遍历添加到新的链表中。

事件复杂度O(2n),空间复杂度(n)

/*** Definition for singly-linked list.* 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) return null;let arr = [];let node = head;while (node) {arr.push(node.val);node = node.next;}let index = 0;let dummy = new ListNode();let current = dummy;while (index !== arr.length) {current.next = new ListNode();current = current.next;current.val = arr[arr.length - index - 1];index++;}return dummy.next;
};

方法二:每次遍历原链表取出一个节点;将该节点采用头插法添加到新链表中。

/*** Definition for singly-linked list.* 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 index = head;let newhead = new ListNode();//遍历链表,并对新链表使用头插法;while (index) {let temp = index;index = index.next;temp.next = newhead.next;newhead.next = temp;}return newhead.next;
};

http://www.lryc.cn/news/607505.html

相关文章:

  • 深入讲讲异步FIFO
  • 向华为学习——IPD流程体系之IPD术语
  • Java函数式编程之【Stream终止操作】【下】【三】【收集操作collect()与分组分区】【下游收集器】
  • 从零开始:Python编程快速入门指南
  • 实战指南:如何将Git仓库中的特定文件夹及其历史完整迁移到另一个仓库
  • vue+element 实现下拉框共享options
  • 智能客服系统实战:多轮对话与知识库检索完整实现
  • 《n8n基础教学》第三节:模拟一个自动化场景
  • Android使用MediaProjectionManager获取游戏画面和投屏
  • C语言-字符串(定义)、字符串函数(strlen、strcat、strcpy、strcmp、strlwr、strupr)
  • 【string类常见接口】
  • Linux系统编程Day3-- Linux常用操作(续)
  • 基于深度学习的医学图像分析:使用Autoencoder实现医学图像去噪
  • Flask 路由系统:URL 到 Python 函数的映射
  • Coze Studio概览(五)--工作流管理
  • 20250801在Ubuntu24.04.2LTS下编译firefly_itx_3588j的Android12时解决boot.img过大的问题
  • 【lucene】FastVectorHighlighter案例
  • 基于线性规划的储能充放电仿真系统
  • Android Frameworks从零开始
  • JSON 对象在浏览器中顺序与后端接口返回不一致的问题
  • 好未来披露2026财年Q1财报:净利润3128万美元,同比大增174%
  • Day 28:类的定义和方法
  • Git 命令使用指南:从入门到进阶
  • MySQL CPU占用过高排查指南
  • 数据处理四件套:NumPy/Pandas/Matplotlib/Seaborn速通指南
  • Agents-SDK智能体开发[3]之多Agent执行流程
  • SN74LVC1G08DBVR 德州仪器(TI)逻辑芯片IC 电源芯片 ESD保护
  • 智慧社区构建——2
  • C语言(02)——标准库函数大全(持续更新)
  • AI Agent 视角:可执行程序的二进制格式,是一场「结构化语言」与「智能解析」的双向奔赴