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

JavaScript递归替换数组负整数为0遇问题,求链表递归实现方案

数组负数替换为0的递归问题修正及链表的递归处理方案

一、数组递归代码的问题分析与修正

你的递归遍历逻辑本身是正确的,会逐个检查数组元素并将负数替换为0,但存在一个关键问题:当递归终止(currentIndex >= array.length)时,函数没有返回处理后的数组,导致整个函数的最终返回值是undefined,所以console.log打印出来的是undefined而非处理后的数组。

修正后的代码

只需在递归终止条件处返回数组即可:

function substitute_negatives(array, currentIndex) {
  if (currentIndex < array.length) {
    if (array[currentIndex] < 0) {
      array[currentIndex] = 0;
    }
    return substitute_negatives(array, currentIndex + 1);
  }
  // 递归终止时返回处理后的数组
  return array;
};

console.log(substitute_negatives([2, -1, 3, -1, 2], 0)); // 输出 [2, 0, 3, 0, 2]

另外,由于数组是引用类型,你也可以不依赖函数返回值,直接打印原数组(但让函数返回处理后的数组更符合常规编程逻辑):

const arr = [2, -1, 3, -1, 2];
substitute_negatives(arr, 0);
console.log(arr); // 输出 [2, 0, 3, 0, 2]

二、链表的递归处理方案

完全可以用递归处理链表的同类需求。假设链表节点结构如下:

class ListNode {
  constructor(val = 0, next = null) {
    this.val = val;
    this.next = next;
  }
}

递归实现思路

  1. 若当前节点为null,终止递归
  2. 检查当前节点值,若为负数则替换为0
  3. 递归处理当前节点的next指针
  4. 返回处理后的节点,维持链表结构

实现代码

function substituteLinkedListNegatives(node) {
  if (!node) return null;
  // 替换负数节点值
  if (node.val < 0) {
    node.val = 0;
  }
  // 递归处理下一个节点
  node.next = substituteLinkedListNegatives(node.next);
  return node;
}

// 测试示例
const head = new ListNode(2, new ListNode(-1, new ListNode(3, new ListNode(-1, new ListNode(2)))));
const processedHead = substituteLinkedListNegatives(head);

// 遍历打印验证结果
let current = processedHead;
const result = [];
while (current) {
  result.push(current.val);
  current = current.next;
}
console.log(result); // 输出 [2, 0, 3, 0, 2]

内容的提问来源于stack exchange,提问作者Sharon Kaufman

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 13:50:16