描述
已知顺序表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