C 链接列表创建链接列表的链接列表

c++ linked list creation linked list of linked list

本文关键字:链接 列表 创建      更新时间:2023-10-16

代码在此行中发送错误 课程[" CS"]。学生=新课程*[1];

我想创建链接的课程列表包含链接的学生列表

这是代码

struct Student{
    string name; 
    int id; 
    int grade; 
    Student(string n, int i, int gd ){
    name=n; 
    id=i;
    grade=gd; 
    }
};
struct Course{
    string C_Name; 
    Student **student;
    int index;
    void add_student(Student *new_student){
    student[++index]=new_student;   
    } 
};
Course course[4];
void init(){
    course["CS"].student=new Course*[1];
}

您的代码不包含任何类型的链接列表,而只包含普通数组。除此之外,最后一行(course["CS"].student=new Course*[1];)包含一些无效的语法。

  • 必须使用积分或枚举类型来访问数组(string S或char[]无法工作)
  • 不允许将Course**分配给Student**对象

链接列表包含每个节点的节点,每个节点都有指向下一个节点的指针。最后一个节点通常具有带有值nullptr(C 11)或0(较旧标准)的指针。注意:还有一个所谓的双链接列表,每个节点还存储一个指向上一个的指针。一个节点包含您要存储的所有数据。示例:

struct Node {
    Node* next;
    // other node data here
};

要创建一个链接列表,您首先以一个节点开始并设置next = nullptr; // 0。要添加另一个节点,只需创建一个新的节点,然后更改第一个节点的指针即可。示例:

Node* node1 = new Node();
node1 -> next = nullptr;
Node* node2 = new Node();
node2 -> next = nullptr;
node1 -> next = node2;

您开始看到模式。要在前面插入,只需创建一个新的Node,然后将其next设置为第一个已经存在的节点即可。要在两个节点之间插入,例如node1node2

node1 -> next = newNode;
newNode -> next = node2;

使它变得不错,通常写一个包装类包装的功能,例如

InsertNodeAt(Node* node, uint index);
Node* GetNodeAt(uint index);
RemoveNodeAt(uint index);

由于您有两种不同类型的对象(StudentCurse),因此您可能需要使用模板并避免为每种类型编写链接列表类。

如果您想自己创建链接列表,我建议您进行一些其他研究(Google是您的朋友),因为我只提到了几件事。

如果您不介意使用C 标准库,则可能有兴趣使用已预制的链接列表类std::forward_list(标准链接列表)和std::list(双链接列表)。

在C 中您没有定义课程["字符串"],因此您不得将" CS"用作课程类型对象的索引和 *。 -student是class 学生的对象,而不是课程 type

#include <iostream>
#include <stdexcept>
 using namespace std;
struct Student{
    string name; 
    int id; 
    int grade; 
    Student(string n, int i, int gd ){
    name=n; 
    id=i;
    grade=gd; 
    }
};
struct Course{
    string C_Name; 
    Student **student;
    int index;
    void add_student(Student *new_student){
    student[++index]=new_student;   
    } 
};
Course course[4];
void init(){
    // Need allocate space for a new object of class "Course"
    Course course;
    course.student = new Student*[1];// "student" is Student type but not Course 
}
int main()
{
    try{
        init();
    }
    catch(...){
        return -1;
    }
    std::cerr <<"your debug info" <<endl;
    return 0;
}

,我认为,在C 中,您可以尝试参考,并且在班级课程的定义中是对班级学生的定义。以这种方式使用打印机可能会导致错误意外。