当前位置:   article > 正文

C++单链表排序_c++对单链表排序

c++对单链表排序
  1. #include<iostream>
  2. #define ElemType int
  3. using namespace std;
  4. typedef struct Node {
  5. ElemType data;
  6. struct Node *next;
  7. };
  8. void Create(Node *&l) { //尾插法
  9. int x;
  10. l->next = NULL; //头结点
  11. Node *s,*r = l; //r为表尾指针
  12. cin >> x;
  13. while (x != -1) {
  14. s = new Node;
  15. s->data = x;
  16. r->next = s;
  17. r = s;
  18. cin >> x;
  19. }
  20. r->next = NULL;
  21. }
  22. void Print(Node *&l) { //输出链表中的数据
  23. Node *p = l->next;
  24. while (p != NULL) {
  25. cout << p->data << " ";
  26. p = p->next;
  27. }
  28. cout << endl;
  29. }
  30. void Delete(Node *&l) { //单链表的删除操作
  31. Node *p = l;
  32. Node *q = l->next; //保存后继指针,防止断链
  33. while (p!= NULL ) {
  34. delete p;
  35. p = q;
  36. if (q != NULL) {
  37. q = q->next;
  38. }
  39. }
  40. }
  41. void Sort(Node *&l) { //采用头插法
  42. Node *p = l->next, *pre;
  43. Node *r = p->next;
  44. p->next = NULL;
  45. p = r;
  46. while (p!=NULL) {
  47. r = p->next;
  48. pre = l;
  49. while (pre->next != NULL&&pre->next->data < p->data) {
  50. pre = pre->next;
  51. }
  52. p->next = pre->next;
  53. pre->next = p;
  54. p = r;
  55. }
  56. }
  57. int main() {
  58. Node *l = new Node; //新建结点,并且创建指针
  59. Create(l);
  60. Print(l);
  61. Sort(l);
  62. Print(l);
  63. Delete(l); //释放内存
  64. system("pause");
  65. return 0;
  66. }
  67. /*
  68. 12 43 56 67 34 32 12 65 -1
  69. */

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/1006957
推荐阅读
相关标签
  

闽ICP备14008679号