基于链表的类_类的实现通过链表

  1 #include <iostream>
  2 #include <string>
  3 using namespace std;
  4 
  5 class Student
  6 {
  7 private:
  8     string name;
  9     int score;
 10 
 11 public:
 12     // 先设置为public 思考 如果是private 如何实现鸭?
 13     Student* next;
 14     Student()
 15     {
 16 
 17     }
 18     Student(string n, int s)
 19     {
 20         name = n;
 21         score = s;
 22     }
 23     void printStuInfo()
 24     {
 25         cout << "name: " << name << " score:" << score << endl;
 26     }
 27 };
 28 class StuLink
 29 {
 30 private:
 31     Student* head;
 32 public:
 33     StuLink()
 34     {
 35         head = NULL;
 36     }
 37     void addStuNode(string n, int s)
 38     {
 39         Student* stu = new Student(n, s);
 40         //添加节点
 41         if (head == NULL)
 42         {
 43             head = stu;
 44             head->next = NULL;
 45         }
 46         else
 47         {
 48             Student* temp = head;
 49             while (temp->next != NULL)
 50             {
 51                 temp = temp->next;
 52             }
 53             temp->next = stu;
 54             stu->next = NULL;
 55         }
 56     }
 57     void printStuNodeInfo()
 58     {
 59         if (head == NULL)
 60         {
 61             cout << "链表为空,没有数据\n";
 62         }
 63         else
 64         {
 65             while (head != NULL)
 66             {
 67                 head->printStuInfo();
 68                 head = head->next;
 69             }
 70         }
 71     }
 72     void releaseStuNode()
 73     {
 74         if (head == NULL)
 75         {
 76             cout << "链表内存为空\n";
 77         }
 78         else
 79         {
 80             Student* temp;
 81             while (head != NULL)
 82             {
 83                 temp = head;
 84                 head = head->next;
 85                 cout << "释放节点内存成功\n";
 86             }
 87         }
 88     }
 89 };
 90 int main()
 91 {
 92     StuLink link;
 93     link.addStuNode("zhangsan", 100);
 94     link.addStuNode("lisi", 90);
 95     link.addStuNode("wangwu", 80);
 96     link.addStuNode("sunliu", 70);
 97     link.printStuNodeInfo();
 98     link.releaseStuNode();
 99 
100     system("pause");
101     return 0;
102 }

 

posted @ 2019-04-19 21:58  littlelittleprince  阅读(907)  评论(0编辑  收藏  举报