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

如何不使用p=p->link,通过多次使用->运算符获取链表最后一个节点

不使用赋值语句实现链表x次->next调用获取尾节点方案

核心要求匹配

已知链表总节点数为x,头指针为p,禁止使用p = p->next类赋值语句,等价实现p->next->next->...(共x次->next调用)的效果,对应你提出的p (->next)*x伪代码需求。

场景1:x为编译期已知常量(C++模板元编程实现)

编译期即可确定x的情况下,用模板递归直接展开为连续的->next调用,生成代码和手写链式调用完全一致,无任何中间赋值:

template<int StepCnt, typename NodeType>
constexpr NodeType* chain_advance(NodeType* head) {
    if constexpr (StepCnt == 0) {
        return head;
    } else {
        return chain_advance<StepCnt - 1>(head->next);
    }
}
// 调用示例,x为编译期常量
Node* tail = chain_advance<x>(p);

场景2:x为运行时动态变量(通用递归实现)

x在运行时才能确定的场景下,通过递归函数的参数传递实现指针递进,全程无原指针赋值操作:

// C语言示例,其他语言可参照逻辑修改
struct ListNode* chain_advance(struct ListNode* cur, int remain_step) {
    if (remain_step <= 0 || cur == NULL) {
        return cur;
    }
    return chain_advance(cur->next, remain_step - 1);
}
// 调用示例
struct ListNode* tail = chain_advance(p, x);

效果验证

两种实现都完全满足要求:

  • 无任何p = p->next类的赋值语句
  • 执行逻辑等价于连续调用x次->next运算符
  • 编译优化后和手写链式调用的性能几乎无差异

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 20:15:03