1 #include<iostream> 2 #include<ctime> 3 using namespace std; 4 typedef struct s{ 5 int value; 6 struct s * next; 7 }list; 8 list * init_list() {//创建不带头结点的链表 9 srand((unsigned)time(NULL)); 10 list *head = new list; 11 list p = head,q; 12 for (int i = 0; i < 5; i++) { 13 q = new list; 14 q->value = rand(); 15 q->next = NULL; 16 p->next = q; 17 p = q; 18 } 19 head = head->next;//删去头节点 20 return head; 21 } 22 void sort_list(list * &head) { //升序 23 /第二版for循环/ 24 list *front, *middle, *back; 25 list *end = NULL;//保存内层循环的结束位置 26 for (head = new list{ 0, head }; (head->next)->next != end; end = middle) { 27 for (front = head, middle = head->next; middle->next != end; front = front->next) { 28 back = middle->next; 29 if (middle->value > back->value) {//交换middle和back 30 middle->next = back->next; 31 back->next = middle; 32 front->next = back; 33 //上面的交换过程之后middle已经变成原来的back,也就是原来的下一个元素 34 } 35 else { 36 middle = middle->next;//不需交换的话middle指向下一个元素 37 } 38 } 39 } 40 head = head->next;//去除空头结点 41 } 42 void print_list(list p) { 43 while (p != NULL) { 44 cout << p->value << “ ”; 45 p = p->next; 46 } 47 cout << endl; 48 } 49 int main() { 50 /创建链表*/ 51 list head=init_list(); 52 /打印随机数创建的链表/ 53 print_list(head); 54 /排序/ 55 sort_list(head); 56 /打印排序后的链表*/ 57 print_list(head); 58 system(“pause”); 59 return 0; 60 }
讯享网

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/196244.html