首页 > 编程语言 > 详细

链表添加节点遍历节点清除节点内存c++实现

时间:2019-04-11 22:41:25      阅读:141      评论:0      收藏:0      [点我收藏+]

  1 #include <iostream>
  2 using namespace std;
  3 
  4 struct Student
  5 {
  6     int score;
  7     Student* next;
  8 };
  9 //创建全局变量
 10 Student* head = NULL; 
 11 //代码改进 
 12 //创建全局变量
 13 Student* pEnd = NULL; 
 14 Student* addNode(int scoreValue);
 15 void printNodeInfo(Student* node);
 16 void releaseNode(Student* node);
 17 int main()
 18 {
 19     addNode(100);
 20     addNode(90);
 21     Student* stuHead = addNode(80);
 22     printNodeInfo(stuHead);
 23     releaseNode(stuHead);
 24     
 25     return 0;
 26 }
 27 //Student* addNode(int scoreValue)
 28 //{
 29 //    Student* stu = new Student;
 30 //    stu -> score = scoreValue;
 31 //    //创建临时节点
 32 //    Student* temp = NULL; 
 33 //    if(head == NULL)
 34 //    {
 35 //        head = stu;
 36 //        //先这样写 等会优化一下 
 37 //        //自己写的时候 漏点这行代码 找了半天的bug 
 38 //        head ->next = NULL;
 39 //
 40 //    }
 41 //    else
 42 //    {
 43 //        //遍历 尾插法插入节点
 44 //        temp = head;
 45 //        while(temp ->next != NULL)
 46 //        {
 47 //            temp = temp ->next;
 48 //        }
 49 //        temp ->next = stu;
 50 //        stu ->next = NULL;
 51 //    }
 52 //    cout << "添加节点成功\n";
 53 //    return head;
 54 //}
 55 //尾插法优化 每次都要遍历节点 优化 创建一个临时节点用来保存尾节点 
 56 //添加时 直接添加到临时节点的尾部 代码实现如下
 57 Student* addNode(int scoreValue)
 58 {
 59     Student* stu = new Student;
 60     stu ->score = scoreValue;
 61     if(head == NULL)
 62     {
 63         head = stu;
 64         pEnd = head;
 65         pEnd ->next = NULL;
 66     }
 67     else
 68     {
 69         pEnd ->next = stu;
 70         pEnd = stu;
 71         pEnd ->next = NULL;
 72     }
 73     cout << "添加节点成功\n";
 74     return head;
 75 }
 76 
 77 void printNodeInfo(Student* node)
 78 {
 79     if(node == NULL)
 80     {
 81         cout << "链表为空\n"; 
 82     }
 83     else
 84     {
 85         while(node != NULL)
 86         {
 87             cout << "score: " << node ->score << endl;
 88             node = node ->next;
 89         }
 90     }
 91 }
 92 void releaseNode(Student* node)
 93 {
 94     //创建临时节点
 95     Student* temp = NULL; 
 96     if(node == NULL)
 97     {
 98         cout << "链表节点内存为空\n";
 99     }
100     else
101     {
102         while(node != NULL)
103         {
104             temp = node;
105             node = node ->next;
106             delete temp;
107             cout << "节点内存清除成功\n";
108         }
109     }
110 }

 


 

链表添加节点遍历节点清除节点内存c++实现

原文:https://www.cnblogs.com/littlelittleprince/p/10692920.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!