You need to enable JavaScript to run this app. C++链表类双构造函数实现:数组初始化方式的问题排查
优惠活动
大模型
产品
解决方案
定价
更多

C++链表类双构造函数实现:数组初始化方式的问题排查

链表类数组构造功能的可运行实现方案

原代码存在的具体问题

  • 类内冗余成员:定义的int arr[]是无固定长度的柔性数组成员,当前场景完全没有使用价值,会引发编译报错
  • 野指针访问:数组入参的构造函数进入执行体时,head指针未完成初始化,直接访问head->val会触发非法内存访问,导致程序直接崩溃
  • 元素重复:错误逻辑中先手动给空head指向的位置写入arr[0]的值,后续循环又从数组下标0开始逐个调用addnode,会导致链表中第一个元素重复存储
  • 传参错误:main函数中实例化链表时传入barr[4]一是访问了长度为4的数组的越界下标位置,二是传入的是int类型的数组元素值,和构造函数要求的int[]数组地址类型不匹配,直接会触发编译报错
  • 边界兼容缺失:如果传入数组长度为0,原有逻辑会直接访问arr[0]触发越界异常

修正后的完整代码

#include <iostream>
using namespace std;

class List {
  class node {
   public:
    int val;
    node* next;
  };

 public:
  node* head;
  List() { head = 0; }
  List(int arr[], int size);

  void addnode(int value) {
    node* newnode = new node();
    newnode->val = value;
    newnode->next = NULL;
    if (head == NULL) {
      head = newnode;
    } else {
      node* temp = head;
      while (temp->next != NULL) {
        temp = temp->next;
      }
      temp->next = newnode;
    }
  }

  void display() {
    if (head == NULL) {
      cout << "List is empty!" << endl;
    } else {
      node* temp = head;
      while (temp != NULL) {
        cout << temp->val << " ";
        temp = temp->next;
      }
      cout << endl;
    }
  }
};

// 修正后的数组入参构造函数实现
List::List(int arr[], int size) {
    // 首先初始化head为空指针,和无参构造逻辑保持一致
    head = 0;
    // 遍历数组逐个添加节点,兼容size为0的空链表场景
    for (int i = 0; i < size; i++) {
        addnode(arr[i]);
    }
}

int main() {
  int barr[4] = {9, 89, 0, 43};
  List* M = new List();
  // 修正传参:直接传入数组名,替换原来越界的 barr[4]
  List* L = new List(barr, 4);

  L->display();
  return 0;
}

代码运行效果

程序编译运行后会输出:9 89 0 43 ,和传入数组的元素顺序完全一致;无参实例化的链表保持空状态,完全匹配两种实例化方式的设计需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.25 14:24:04