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

如何将手动打印链表指定索引节点的代码改为适配任意索引的通用版本

链表打印节点通用版本改造方案

核心改造逻辑:把硬编码的多层next指针访问替换为循环遍历逻辑,不管输入的合法索引是多少,都可以自动移动指针到对应节点,不需要逐一枚举判断。

优化后完整代码(推荐版本,仅需一次遍历)

void Linkedlist::printNode(int nodeOffset)
{
    if (head == NULL) {
        cout << "List empty." << endl;
        return;
    }

    Node *curr = head;
    int step = 0;
    // 一次遍历同时完成索引合法性检查+节点定位
    while (curr != NULL && step < nodeOffset - 1) {
        curr = curr->next;
        step++;
    }

    // 遍历结束后指针为空则说明索引超出链表长度
    if (curr == NULL) {
        cout << "Index out of range" << endl;
        return;
    }

    // 直接打印当前节点数据
    cout << "Integer at index " << nodeOffset - 1 << ": " << curr->data << endl;
}

兼容原有遍历逻辑的版本(逻辑更直观)

如果你希望保留先计算链表总长度再校验索引的原有写法,可使用以下版本:

void Linkedlist::printNode(int nodeOffset)
{
    Node *temp1 = head;
    int ListLen = 0;

    if (head == NULL) {
        cout << "List empty." << endl;
        return;
    }

    // 计算链表总长度
    while (temp1 != NULL) {
        temp1 = temp1->next;
        ListLen++;
    }

    // 校验索引合法性
    if (ListLen < nodeOffset) {
        cout << "Index out of range" << endl;
        return;
    }

    // 循环移动指针到目标节点
    Node *target = head;
    for (int i = 1; i < nodeOffset; i++) {
        target = target->next;
    }

    cout << "Integer at index " << nodeOffset - 1 << ": " << target->data << endl;
}

改造说明

  • 完全兼容原有入参规则:nodeOffset仍从1开始计数,输出的索引还是对应0开始的编号,原有调用逻辑无需任何修改
  • 删掉了所有硬编码的分支判断,支持任意合法索引的节点打印
  • 推荐版本优化了遍历效率,将原实现的两次遍历缩减为一次,常数开销更低

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 12:24:00