weixin_43306709 2022-03-06 12:01 采纳率: 77.3%
浏览 46
已结题

我想请问一下,这个方法创建链表报的错误,怎么解决呀!

问题遇到的现象和发生背景
问题相关代码,请勿粘贴截图
#ifndef MYLIST_H
#define MYLIST_H
#include <iostream>
using namespace std;
template <class T>
struct ListNode
{
    ListNode<T> *next;
    T value;
    ListNode(int n) : value(n), next(NULL) {}
};

template <class T>
class List
{
private:
    ListNode<T> *head;

public:
    List();
    void createList1(int n);
    void display();
};
//构造函数
template <class T>
List<T>::List()
{
    head = new ListNode<T>;
    head->next = NULL;
}
//创建元素为n个的链表,尾插法
template <class T>
void List<T>::createList1(int n)
{
    for (int i = 0; i < n; i++)
    {
        T j;
        cout << "请依次输入元素的值:" << endl;
        cin >> j;
        ListNode<T>* q = new ListNode<T>(j);
        q->next = head->next;
        head->next = q;
    }
}
template <class T>
void List<T>::display()
{
    ListNode<T> *p;
    p = head->next;
    while (p)
    {
        cout << p->value << endl;
        p = p->next;
    }
}
#endif

using namespace std;

int main()
{
List s1;
s1.createList1(3);
s1.display();
return 0;
}

运行结果及报错内容

./mylist.h:28:16: error: no matching constructor for initialization of 'ListNode'
head = new ListNode;
^
main.cpp:8:15: note: in instantiation of member function 'List::List' requested here
List s1;
^
./mylist.h:10:5: note: candidate constructor not viable: requires single argument 'n', but no arguments were provided
ListNode(int n) : value(n), next(NULL) {}
^
./mylist.h:6:8: note: candidate constructor (the implicit copy constructor) not viable: requires 1 argument, but 0 were provided
struct ListNode
^
1 error generated.

我想要达到的结果
  • 写回答

1条回答 默认 最新

  • orange4reg 2022-03-06 15:15
    关注
    head = new ListNode<T>;
        head->next = NULL;
    两个改成 head = new ListNode<T>(0);即可
    
    List s1 改 List<int> s1
    
    ListNode(int n)ListNode(T n) 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录

报告相同问题?

问题事件

  • 系统已结题 3月14日
  • 已采纳回答 3月6日
  • 创建了问题 3月6日

悬赏问题

  • ¥15 对于知识的学以致用的解释
  • ¥50 三种调度算法报错 有实例
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败