前端知识学习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;
}
相关推荐
尘世中一位迷途小书童2 小时前
用 Cesium 撸了一个森林火情监控大屏,弧线、粒子、发光效果都齐了
前端·javascript
IT_陈寒2 小时前
垃圾回收器选错了,我的Java服务内存炸了
前端·人工智能·后端
月光下的丝瓜3 小时前
Flutter 国内安装指南
前端·flutter
先吃饱再说3 小时前
JavaScript中`this` 的“千层套路”:从默认绑定到箭头函数的五种指向
javascript
玄星啊3 小时前
AI 编程的第 30 天,我怀念古法 Coding 了
前端·ai编程
Jolyne_3 小时前
Angular基础速通
前端·angular.js
foxire3 小时前
基于nodejs实现服务端内核引擎
javascript
锋行天下4 小时前
半秒开!还有谁!!!
前端·vue.js·架构
代码搬运媛5 小时前
git 下中文文件名乱码问题解决
前端
CaffeinePro5 小时前
告别知识点零散!React零基础通关,从环境搭建到Ant Design页面实战
前端·react.js