C 链接列表创建链接列表的链接列表
c++ linked list creation linked list of linked list
代码在此行中发送错误 课程[" 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
设置为第一个已经存在的节点即可。要在两个节点之间插入,例如node1
和node2
:
node1 -> next = newNode;
newNode -> next = node2;
使它变得不错,通常写一个包装类包装的功能,例如
InsertNodeAt(Node* node, uint index);
Node* GetNodeAt(uint index);
RemoveNodeAt(uint index);
由于您有两种不同类型的对象(Student
和Curse
),因此您可能需要使用模板并避免为每种类型编写链接列表类。
如果您想自己创建链接列表,我建议您进行一些其他研究(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 中,您可以尝试参考,并且在班级课程的定义中是对班级学生的定义。以这种方式使用打印机可能会导致错误意外。
- 从链接列表c++中删除一个项目
- 读取文件的最后一行并输入到链接列表时出错
- 下面是我为检测链接列表中的循环而制作的代码
- 有人能帮我处理这个链接列表吗?C++
- C++ 创建包含链表和字符串的对象的链接列表时出错
- 你能检查一下为什么在这个代码中从链接列表中删除项目不起作用吗
- 为什么它只打印双链接列表的第一个值,而我的程序却崩溃了
- 链接列表运算符重载没有打印出我想要的内容
- 链接列表在 cpp 中包含不同的对象类
- 创建一个棋盘格或"Interweave"两个链接列表。IE 更改两个链表的指针
- 如何在构建链接列表时调整头、尾指针
- Shared_ptr双链接列表内存泄漏
- 为什么每当我尝试运行此链接列表删除功能时都会收到分段错误错误?
- 在链接列表中查找元素 - C++
- 删除链接列表中剩余的最后一个节点
- 只有我的"链接列表"中的第一个节点正在打印
- 避免在使用链接列表从 deque 中删除最后一个节点时出现内存泄漏
- C++ 分段错误:11 错误,同时编码将两个数字相加的链接列表
- 如何在C / C++中正确实现链接列表而不会使程序崩溃
- 将元素插入链接列表