前端知识学习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;
}
相关推荐
本郡主是喵35 分钟前
用 TypeScript 进行 Truffle 测试
学习·区块链
10年前端老司机1 小时前
Promise 常见面试题(持续更新中)
前端·javascript
潘小安1 小时前
跟着 AI 学 (一)- shell 脚本
前端·ci/cd·vibecoding
武文斌772 小时前
复习总结最终版:单片机
linux·单片机·嵌入式硬件·学习
clownAdam2 小时前
Chrome性能优化秘籍
前端·chrome·性能优化
@Kerry~2 小时前
phpstudy .htaccess 文件内容
java·开发语言·前端
sealaugh323 小时前
AI(学习笔记第十二课) 使用langsmith的agents
人工智能·笔记·学习
QZ_orz_freedom3 小时前
学习笔记--事务管理
笔记·学习
WebDesign_Mu4 小时前
为了庆祝2025英雄联盟全球总决赛开启,我用HTML+CSS+JS制作了LOL官方网站
javascript·css·html
@PHARAOH4 小时前
WHAT - 前端性能指标(交互和响应性能指标)
前端·交互