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

如何在函数中使用链表ADT?队列复制函数编译报错求解

错误原因

  1. 类型混用:isEmpty、enqueue、getFirst、dequeue都是operations类的成员方法,你错误将copyQueue的入参声明为Node*类型,导致调用节点类不存在的成员触发前4项报错;同时函数返回值声明为Node*,但实际返回operations*类型的q2,触发第5项类型转换报错。
  2. 作用域问题:q2是copyQueue内部的局部变量,main函数未接收返回值就直接调用,会触发未定义变量报错。
  3. 逻辑问题:原实现调用q1->dequeue()会清空原队列的所有元素,不符合队列复制的需求。
  4. 语法错误:C++ 布尔真值为小写true,大写True会触发未定义标识符报错。

修复方案

首先修改copyQueue的入参、返回值类型为operations*,改为遍历原队列的节点完成复制,不修改原队列结构;其次在main中接收copyQueue的返回值赋值给q2变量。

修复后完整代码

#include<iostream>
#include "Queue.h"
using namespace std;

operations* copyQueue(operations* q1)
{
    operations *q2 = new operations();
    // 遍历原队列节点复制,不改动原队列结构
    Node* curr = q1->front;
    while(curr != nullptr)
    {
        q2->enqueue(curr->item);
        curr = curr->next;
    }
    return q2;
}

int main()
{
    operations *q1 = new operations();

    int temp, n;
    cout << "Enter queue size: ";
    cin >> n;
    cout << "Enter data to copy: ";
    for( int i = 0 ; i < n ; i++ )
    {
        cin >> temp;
        q1->enqueue(temp);
    }
    // 接收复制后的队列
    operations* q2 = copyQueue(q1);
    cout << "Copied Queue = ";
    q2->display();

    // 可选:补充内存释放逻辑避免泄漏
    // delete q1; delete q2;
    return 0;
}

额外注意

如果你的Node.h中item成员是私有属性,需要将其改为public,或者给operations类添加Node的友元声明,否则访问curr->item会触发权限报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 21:06:01