实验要求: main 函数中利用单向链表类 SingleLinkedList, 定义和初始化一个 Student 类型的线性链表,在表中添加(push_back)和插入(insert)新的元素。
结点的构造
template<typename T>
class SLNode
{
public:
T _data;
SLNode<T>* next;
SLNode()
{
this->_data = NULL;
this-> next = NULL;
}
};
链表的实现
template<typename T>
class SingleLinkedList
{
private:
SLNode<T>* _head;
int _count;
public:
SingleLinkedList()
{
SLNode<T>* _head = NULL;
this->_count = NULL;
}
void push_back(SingleLinkedList* L, T data)
{
SLNode<T>* new_node = new SLNode();
new_node->_data = data;
new_node->next = NULL;
SLNode<T>* last_node = L->_head;
for (int i = 0; i < _count; i++)
{
last_node = last_node->next;
}
new_node->next = last_node->next;
last_node->next = new_node;
}
void insert(SingleLinkedList* L, int pos, T data)
{
if (L == NULL)
{
pos = 0;
}
SLNode<T>* new_node = new SLNode();
new_node->_data = data;
new_node->next = NULL;
SLNode<T>* pos_node = L->_head;
for (int i = 0; i < pos; i++)
pos_node = pos_node->next;
new_node->next = pos_node->next;
pos_node->next = new_node;
L->_count++;
}
void show(SingleLinkedList* L)
{
if (L->_count == 0)
cout << "该链表中没有数据" << endl;
else {
SLNode<T>* pcurrent = L->_head->next;
while (pcurrent != NULL)
{
cout << pcurrent->_data << endl;
pcurrent = pcurrent->next;
}
cout << endl;
}
}
};
测试函数
int main()
{
Student s1 = { 001,"桑桑",18.0f,88.0l };
Student s2 = { 002,"稚稚",8.0f,77.0l };
Student s3 = { 000,"渊渊",25.0f,99.0l };
SingleLinkedList<Student> L1;
cout << s1 << endl;
L1.push_back(&L1,s1);
L1.push_back(&L1,s2);
cout << s1 << endl;
L1.insert(&L1, 0, s3);
L1.show(&L1);
}
Student类
class Student
{
public:
Student(int id, string name, float age, double score);
~Student();
friend ostream& operator<<(ostream&os, const Student&s)
{
os << "学号:" << s._id << " 姓名:" << s._name << " 年龄" << s._age << " 成绩:" << s._score << endl;
return os;
}
string str()
{
cout << "内部输出:" << endl;
cout << "学号:" << _id << " 姓名:" << _name << " 年龄" << _age << " 成绩:" << _score << endl;
return "\n";
};
Student& operator =(const Student&x)
{
this->_id = x._id;
this->_age = x._age;
this->_score = x._score;
this->_name = x._name;
}
private:
int _id;
string _name;
float _age;
double _score;
};
Student::Student(int id, string name, float age, double score)
{
_id = id;
_name = name;
_age = age;
_score = score;
}
Student::~Student()
{
}
报错
已启动生成…
1>------ 已启动生成: 项目: ex4p4, 配置: Debug x64 ------
1>p4.cpp
1>C:\Users\86150\source\repos\ex3\dsa\SingledLinkedList.h(83,1): error C2514: “SLNode”: 无法构建类模板
1>C:\Users\86150\source\repos\ex3\dsa\SingledLinkedList.h(7): message : 参见“SLNode”的声明
1>C:\Users\86150\source\repos\ex3\dsa\SingledLinkedList.h(83): message : 查看对正在编译的 类 模板 实例化“SingleLinkedList<T>”的引用
1>已完成生成项目“ex4p4.vcxproj”的操作 - 失败。
========== 生成: 成功 0 个,失败 1 个,最新 1 个,跳过 0 个 ==========
错误 C2514 “SLNode”: 无法构建类模板 ex4p4 C:\Users\86150\source\repos\ex3\dsa\SingledLinkedList.h 83 //83是最后一行,有点迷惑