- #include <iostream>
- #include <string>
- using namespace std;
- class Student
- {
- private:
- string name;
- int score;
- public:
- // 先设置为 public 思考 如果是 private 如何实现鸭?
- Student* next;
- Student()
- {
- }
- Student(string n, int s)
- {
- name = n;
- score = s;
- }
- void printStuInfo()
- {
- cout <<"name:" << name << "score:" << score << endl;
- }
- };
- class StuLink
- {
- private:
- Student* head;
- public:
- StuLink()
- {
- head = NULL;
- }
- void addStuNode(string n, int s)
- {
- Student* stu = new Student(n, s);
- // 添加节点
- if (head == NULL)
- {
- head = stu;
- head->next = NULL;
- }
- else
- {
- Student* temp = head;
- while (temp->next != NULL)
- {
- temp = temp->next;
- }
- temp->next = stu;
- stu->next = NULL;
- }
- }
- void printStuNodeInfo()
- {
- if (head == NULL)
- {
- cout <<"链表为空, 没有数据 \ n";
- }
- else
- {
- while (head != NULL)
- {
- head->printStuInfo();
- head = head->next;
- }
- }
- }
- void releaseStuNode()
- {
- if (head == NULL)
- {
- cout <<"链表内存为空 \ n";
- }
- else
- {
- Student* temp;
- while (head != NULL)
- {
- temp = head;
- head = head->next;
- cout << "释放节点内存成功 \ n";
- }
- }
- }
- };
- int main()
- {
- StuLink link;
- link.addStuNode("zhangsan", 100);
- link.addStuNode("lisi", 90);
- link.addStuNode("wangwu", 80);
- link.addStuNode("sunliu", 70);
- link.printStuNodeInfo();
- link.releaseStuNode();
- system("pause");
- return 0;
- }
来源: http://www.bubuko.com/infodetail-3029465.html