前端知识学习24.3.19

如何反转一个链表

三个指针,一个指向头节点,另外两个用来指向头节点前后两个节点的位置

javascript 复制代码
// 定义链表节点类
class ListNode {
  constructor(val) {
    this.val = val;
    this.next = null;
  }
}

// 定义反转链表函数
function reverseLinkedList(head) {
  let prev = null;
  let current = head;
  
  while (current !== null) {
    const nextTemp = current.next;
    current.next = prev;
    prev = current;
    current = nextTemp;
  }
  
  return prev; // 返回反转后的头节点
}

// 示例用法
const head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3);
head.next.next.next = new ListNode(4);
head.next.next.next.next = new ListNode(5);

console.log("原始链表:");
let current = head;
while (current !== null) {
  console.log(current.val);
  current = current.next;
}

const reversedHead = reverseLinkedList(head);

console.log("反转后的链表:");
let reversedCurrent = reversedHead;
while (reversedCurrent !== null) {
  console.log(reversedCurrent.val);
  reversedCurrent = reversedCurrent.next;
}
相关推荐
胡萝卜术1 小时前
从API调用到手写LRU:力扣146「LRU缓存」的哈希表+双向链表终极进化之路
前端·javascript·面试
科技道人1 小时前
记录 默认置灰/禁用 app ‘Search Engine Selector‘ 的disable按钮
开发语言·前端·javascript
天疆说2 小时前
Zotero Connector 在 Edge 里找不到桌面 Zotero(Linux / Zotero 9.0.6 / Edge 150)
linux·前端·edge
李伟_Li慢慢3 小时前
02-从硬件说起WebGL
前端·three.js
xian_wwq4 小时前
【学习笔记】模型权重管理:Safetensors与私有化Hub(23/35)
笔记·学习
kyriewen4 小时前
看了微软几万人用AI编程的数据——效率涨24%的代价没人提
前端·ai编程·claude
2601_963771374 小时前
How to Scale Your WordPress Store Traffic in 2026
前端·php·plugin
亿元程序员4 小时前
老板说我的3D箭头游戏用来做试玩太普通了,没人想玩,让我变点花样...
前端
其实防守也摸鱼4 小时前
运维--学习阶段问题解答(1)(自测)
linux·运维·服务器·数据库·学习·自动化·命令模式
ctrl_v助手4 小时前
Halcon学习笔记2
人工智能·笔记·学习