当前位置: 首页 > 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.xdnf.cn/news/1225837.html

相关文章:

  • python+pyside6的简易画板
  • Gitee
  • Dify API接口上传文件 postman配置
  • SpringAI智能客服Function Calling兼容性问题解决方案
  • 隧道安全监测哪种方式好?精选方案与自动化监测来对比!
  • 理解HTTP协议
  • BIFU币富探索合规新路径 助力用户玩转RWA
  • npm报错:npm install 出现“npm WARN old lockfile”
  • 机器学习——逻辑回归(LogisticRegression)的核心参数:以约会数据集为例
  • Linux中Docker Swarm介绍和使用
  • Leetcode 10 java
  • linux81 shell通配符:[list],‘‘ ``““
  • python文件操作:读取文件内容read
  • 噪声对比估计(NCE):原理、演进与跨领域应用
  • 【深度学习①】 | Numpy数组篇
  • C#线程同步(二)锁
  • 国产开源大模型崛起:使用Kimi K2/Qwen2/GLM-4.5搭建编程助手
  • Go语言中的盲点:竞态检测和互斥锁的错觉
  • ctfshow_web签到题
  • 从内部保护你的网络
  • 江协科技STM32 12-2 BKP备份寄存器RTC实时时钟
  • TwinCAT3编程入门2
  • 从 0 到 1 认识 Spring MVC:核心思想与基本用法(下)
  • 自动化框架pytest
  • 【Kubernetes 指南】基础入门——Kubernetes 集群(二)
  • 雷达微多普勒特征代表运动中“事物”的运动部件。
  • Ubuntu 开启wifi 5G 热点
  • p5.js 3D模型(model)入门指南
  • ubuntu 镜像克隆
  • hadoop.yarn 带时间的LRU 延迟删除