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 }
原文:https://www.cnblogs.com/littlelittleprince/p/10692920.html