前端知识学习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;
}
相关推荐
胡萝卜术8 小时前
当大模型遇上浏览器:用 React + WebGPU 在前端跑通 DeepSeek-R1 的实战笔记
前端·javascript·面试
不好听6138 小时前
Tailwind CSS 原子化 CSS 完全入门:为什么现代前端开发都在用?
前端·css
人间凡尔赛8 小时前
Next.js 16 生产级实战:Cache Components + View Transitions 完整指南
开发语言·javascript·ecmascript
触底反弹8 小时前
🔥 React 零基础入门(上):环境搭建 + JSX 深度解析
前端·react.js·typescript
why技术9 小时前
分享一套我一直在使用的 AICoding 组合拳,小而美的典范。
前端·后端·ai编程
朦胧之9 小时前
AI应用-消费流式输出
前端·javascript·ai编程
小林ixn9 小时前
在浏览器跑通 15 亿参数大模型:我用 React + WebGPU 复刻了 DeepSeek-R1
前端·react.js·前端框架
Csvn10 小时前
容器查询 @container 实战:告别无休止的媒体查询
前端
世人万千丶11 小时前
鸿蒙Flutter TextStyle样式配置
学习·flutter·harmonyos·鸿蒙
吃着火锅x唱着歌11 小时前
Effective C++ 学习笔记 条款37 绝不重新定义继承而来的缺省参数值
c++·笔记·学习