前端知识学习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;
}
相关推荐
鬓戈23 分钟前
Rust 语言与 AI 应用生态调研及学习路径
人工智能·学习·rust
传奇开心果编程29 分钟前
【SwiftUI娓娓道来】第3课:让界面活起来——交互与动画指南
学习·macos·ui·ios·swiftui·swift
xian_wwq1 小时前
【学习笔记】等保合规安全基线核查实战
笔记·学习
Csvn1 小时前
并发模式:让渲染学会排队、插队和让路
前端
可乐鸡翅yeah_1 小时前
新手梳理:M3U8 线上问题,哪些是前端锅,哪些是后端锅
前端·ios·音视频·实时音视频·m3u8·音视频在线播放
Flynt1 小时前
Linear 用 1000 个 PR 换掉 styled-components,我写了 200 个按钮,把这笔账复现了一遍
前端·css·preact
传奇开心果编程1 小时前
【Jetpack Compose进阶学与练】第14课:系列收尾复习总结;Compose项目常见坑点汇总;学习路线与后续学习方向
android·学习·ui·kotlin·android jetpack
yangmu32032 小时前
发动机是怎么把油变成动力的:四冲程内燃机原理拆解
学习
m4Rk_2 小时前
【论文阅读】Agent 记忆机制(81):EMR——用情景记忆避免 Agent 在多步推理中反复绕圈
论文阅读·人工智能·学习·开源·github
海海不掉头发2 小时前
阶段五_实验34-38_学习总结
深度学习·神经网络·学习·机器学习