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

Rust修改node.next编译报错:LeetCode第2题两数相加链表插入问题

错误根因

你调用as_ref()获取到的是链表节点的不可变共享引用,自然无法通过该引用修改节点的next字段,这是Rust借用规则的基础限制。

修复后的完整代码

fn insert(mut head: Option<Box<ListNode>>, new_node: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
    if head.is_none() {
        return new_node;
    }

    // 拿可变引用遍历节点
    let mut tail = head.as_mut();
    loop {
        let node = tail.unwrap();
        if node.next.is_none() {
            node.next = new_node;
            break;
        }
        tail = node.next.as_mut();
    }

    head
}

关键改动点

  • 给参数head添加mut修饰:我们需要获取head内部节点的可变引用,必须先声明head本身是可变的
  • 将所有as_ref()替换为as_mut():获取节点的可变引用,才有权限修改节点的next字段
  • 把== None判断替换为is_none(),属于Rust惯用写法,逻辑和原写法完全等价

内容的提问来源于stack exchange,提问作者Jim Jin

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 15:45:07