标签:dat int next 链表 面向对象 Link MyClass ptr
原文链接:http://www.cnblogs.com/yewei/archive/2013/03/01/2939127.html描述
已知顺序表L递增有序,编写一个算法,将X插入到线性表的适当位置上,以保持线性表的有序性!
样例输入
5 12 23 34 45 56 30
样例输出
12 23 30 34 45 56
以前链表的写法都是面向过程的,而面向对象的写法使得程序更具简洁性,当然,更重要的是OOP的思想
1 //: 在顺序表中插入元素 2 #include <iostream> 3 4 using namespace std; 5 6 class MyClass { 7 public: 8 struct Link { 9 int data; 10 Link* next; 11 }*head, *tail; 12 13 MyClass(); 14 15 void push(const int&); 16 void insert_value(const int&); 17 void print_list(); 18 void cleanUp(); 19 }; 20 21 MyClass::MyClass() { 22 head = tail = NULL; 23 } 24 25 void MyClass::push(const int& dat) { 26 Link* ptr = new Link; 27 ptr->data = dat; 28 ptr->next = NULL; 29 if (head == NULL) { 30 head = tail = ptr; 31 } 32 else { 33 tail->next = ptr; 34 tail = ptr; 35 } 36 return ; 37 } 38 39 void MyClass::insert_value(const int& dat) { 40 Link* front = NULL; 41 Link* back = head; 42 bool isInserted = false; 43 44 while (isInserted == false) { 45 if (back->data >= dat) { 46 Link* newNode = new Link; 47 newNode->data = dat; 48 newNode->next = back; 49 if (front == NULL) 50 head = newNode; 51 else 52 front->next = newNode; 53 54 isInserted = true; 55 } 56 front = back; 57 back = back->next; 58 }// End of While 59 return ; 60 } 61 62 void MyClass::print_list() { 63 bool isSpace = false; 64 Link* ptr = head; 65 while (ptr != NULL) { 66 if (isSpace) { 67 cout << ' ' << ptr->data; 68 } 69 else { 70 isSpace = true; 71 cout << ptr->data; 72 } 73 ptr = ptr->next; 74 }// End of While 75 cout << endl; 76 return ; 77 } 78 79 void MyClass::cleanUp() { 80 while (head != NULL) { 81 Link* oldHead = head; 82 head = head->next; 83 delete oldHead; 84 }// End of While 85 } 86 87 int main() { 88 int listLen, dat; 89 90 while (cin >> listLen) { 91 MyClass solver; 92 for (int i = 0; i < listLen; ++i) { 93 cin >> dat; 94 solver.push(dat); 95 } 96 97 cin >> dat; 98 solver.insert_value(dat); 99 solver.print_list(); 100 solver.cleanUp(); 101 }// End of While 102 return 0; 103 } ///:~
转载于:https://www.cnblogs.com/yewei/archive/2013/03/01/2939127.html
标签:dat,int,next,链表,面向对象,Link,MyClass,ptr 来源: https://blog.csdn.net/weixin_30824479/article/details/98986288
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。