前端知识学习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;
}
相关推荐
yuzhiboyouye14 小时前
web前端英语面试
前端·面试·状态模式
canonical_entropy15 小时前
下一代低代码渲染框架 nop-chaos-flux 的设计原则
前端·低代码·前端框架
东方小月15 小时前
5分钟搞懂Harness Engineering(驾驭工程):从提示词到AI Agent的进化之路
前端·后端·架构
我叫黑大帅16 小时前
为什么需要 @types/react?解决“无法找到模块 react 的声明文件”报错
前端·javascript·面试
之歆16 小时前
DAY_21JavaScript 深度解析:数组(Array)与函数(Function)(一)
前端·javascript
XinZong16 小时前
【AI社交】基于OpenClaw自研轻量化AI社交平台实战
前端
Le_ee17 小时前
ctfweb:php/php短标签/.haccess+图片马/XXE
开发语言·前端·php
爱上好庆祝17 小时前
学习js的第七天(wed APIs的开始)
前端·javascript·css·学习·html·css3
KaMeidebaby18 小时前
卡梅德生物技术快报|冻干工艺开发:注射用心肌肽全流程参数优化与工程化方案
前端·其他·百度·新浪微博
ooseabiscuit18 小时前
Laravel6.x核心优化与特性全解析
android·开发语言·javascript