前端知识学习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;
}
相关推荐
C_心欲无痕22 分钟前
nginx - alias 和 root 的区别详解
运维·前端·nginx
charlie1145141912 小时前
嵌入式的现代C++教程——constexpr与设计技巧
开发语言·c++·笔记·单片机·学习·算法·嵌入式
好奇龙猫2 小时前
【AI学习-comfyUI学习-三十二节-FLXU原生态反推+controlnet depth(UNion)工作流-各个部分学习】
人工智能·学习
我是苏苏3 小时前
Web开发:C#通过ProcessStartInfo动态调用执行Python脚本
java·服务器·前端
无羡仙3 小时前
Vue插槽
前端·vue.js
好奇龙猫3 小时前
【大学院-筆記試験練習:数据库(データベース問題訓練) と 软件工程(ソフトウェア)(7)】
学习
哈__3 小时前
React Native 鸿蒙跨平台开发:PixelRatio 像素适配
javascript·react native·react.js
用户6387994773054 小时前
每组件(Per-Component)与集中式(Centralized)i18n
前端·javascript
SsunmdayKT4 小时前
React + Ts eslint配置
前端