You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JavaScript中遍历链表并删除值为k的节点

优雅处理数组转链表并删除指定值节点

看到你提到用reduceRight把数组转成链表的方法确实很巧妙,但核心需求是要遍历链表删除值为k的节点对吧?我来一步步拆解怎么实现这个功能。

首先先看你给出的数组转链表代码,它利用reduceRight从后往前遍历数组,把每个元素包装成链表节点,但注意原代码里的参数顺序写反了,reduceRight的回调参数是(累加器, 当前值),所以正确的写法应该是这样:

function arrayToLinkedList(arr) {
  return arr.reduceRight((nextNode, currentValue) => {
    return { value: currentValue, next: nextNode };
  }, null);
}

这样生成的链表结构才是正确的{value: 元素值, next: 下一个节点}格式。

接下来是核心的删除链表中指定值节点的逻辑,因为链表没有数组那样便捷的遍历/过滤方法,得手动处理指针,需要覆盖几种场景:头节点就是要删除的节点、中间节点要删除、尾节点要删除。

我给你写一个完整的可运行实现:

// 数组转链表工具函数
function arrayToLinkedList(arr) {
  return arr.reduceRight((nextNode, currentValue) => {
    return { value: currentValue, next: nextNode };
  }, null);
}

// 删除链表中所有值为k的节点
function removeKFromList(head, k) {
  // 先处理头节点连续等于k的情况(比如链表开头是[3,3,1,...])
  while (head !== null && head.value === k) {
    head = head.next;
  }
  
  // 如果处理后头节点为空,直接返回空链表
  if (head === null) {
    return null;
  }
  
  // 遍历处理中间和尾节点
  let current = head;
  while (current.next !== null) {
    if (current.next.value === k) {
      // 跳过要删除的节点,直接指向它的下一个节点
      current.next = current.next.next;
    } else {
      // 没有要删除的节点,正常移动指针
      current = current.next;
    }
  }
  
  return head;
}

// 测试用例
let l = [3, 1, 2, 3, 4, 5]; 
let k = 3;
let linkedList = arrayToLinkedList(l);
let resultList = removeKFromList(linkedList, k);

// 辅助函数:打印链表的所有值(转成数组输出更直观)
function printLinkedList(head) {
  let current = head;
  const values = [];
  while (current !== null) {
    values.push(current.value);
    current = current.next;
  }
  console.log(values); // 输出 [1,2,4,5]
}
printLinkedList(resultList);

如果想把数组转链表和删除操作合并成一个函数,也可以这样简化:

function removeKFromList(arr, k) {
  // 第一步:数组转链表
  let head = arr.reduceRight((nextNode, currentValue) => {
    return { value: currentValue, next: nextNode };
  }, null);
  
  // 第二步:执行删除逻辑(和上面一致)
  while (head !== null && head.value === k) {
    head = head.next;
  }
  
  if (head === null) {
    return null;
  }
  
  let current = head;
  while (current.next !== null) {
    if (current.next.value === k) {
      current.next = current.next.next;
    } else {
      current = current.next;
    }
  }
  
  return head;
}

内容的提问来源于stack exchange,提问作者Tyler L

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:54:44