当前位置:   article > 正文

单链表的建立与排序_编写一个创建有5个结点的链表的算法

编写一个创建有5个结点的链表的算法

指针这一块的确实博大精深,不愧是c的精髓

一个字妙啊!

  1. /*
  2. struct Node {
  3. int Element; // 节点中的元素为整数类型
  4. struct Node * Next; // 指向下一个节点
  5. };
  6. 从键盘输入5个整数,将这些整数插入到一个链表中,并按从小到大次序排列,最后输出这些整数。
  7. 5 3 4 2 1
  8. 1 2 3 4 5
  9. */
  10. #include<iostream>
  11. using namespace std;
  12. typedef struct node
  13. {
  14. int data;
  15. struct node* next;
  16. }*lnode;
  17. //建立单链表
  18. void createNode(lnode &head)
  19. {
  20. lnode p; int x;//定义节点p和值x
  21. head = new node;//为头结点开辟空间,用head接收
  22. head->next = NULL;//为头结点的下一个赋空
  23. cout << "输入5个节点的值,输入9999退出循环" << endl;
  24. int k = 0;
  25. while (1)//while循环创立下一个节点
  26. {
  27. //if (x == 9999) break;
  28. if (k == 5) break;
  29. cin >> x;
  30. p = new node;//p与head首先无关联
  31. p->data = x;
  32. p->next = head->next;
  33. head->next = p;
  34. k++;
  35. }
  36. }
  37. //遍历链表
  38. void track(lnode head)
  39. {
  40. lnode p ;
  41. for ( p = head->next; p!=NULL; p = p->next)
  42. cout << p->data<<" ";
  43. }
  44. //计算链表长度
  45. int calculateLength(lnode head)
  46. {
  47. int count = 0;
  48. lnode p = head->next;
  49. while (p)
  50. {
  51. count++;
  52. p = p->next;
  53. }
  54. return count;
  55. }
  56. //查 统计链表中待查找元素的个数
  57. int search(lnode head,int x)
  58. {
  59. lnode p = head->next;
  60. int count = 0;
  61. while (p)
  62. {
  63. if (p->data == x) count++;
  64. p = p->next;
  65. }
  66. return count;
  67. }
  68. //增 链表的元素插入.在pos处插入元素x
  69. void insert(lnode head, int pos, int x)
  70. {
  71. lnode p = head;
  72. for (int i = 0; i < pos; i++)//0号位置是head的下一个元素
  73. {
  74. p = p->next;
  75. }
  76. lnode t = new node;
  77. t->data = x;
  78. t->next = p->next;
  79. p->next = t;
  80. }
  81. //删 删除表中所有元素等于x的值
  82. void Delete(node *head, int x) {
  83. node *pre, *p;
  84. pre = head;
  85. p = head->next;
  86. while (p) {
  87. if (p->data = x) {
  88. pre->next = p->next; //删除p所指向的结点
  89. delete p;
  90. p = pre->next; //重新给p赋值
  91. }
  92. else {
  93. pre = p; //pre永远指向待删结点的前一个
  94. p = p->next;
  95. }
  96. }
  97. }
  98. int main()
  99. {
  100. lnode head,p,q;
  101. createNode(head);
  102. //冒泡排序
  103. /*cout << "开始排序" << endl;
  104. int n = 5;
  105. for (int i = 0; i < 5; ++i) {
  106. p = head->next;
  107. for (int j = 0; j < 4 - i; ++j) {
  108. if (p->data > p->next->data) {
  109. int temp = p->data;
  110. p->data = p->next->data;
  111. p->next->data = temp;
  112. }
  113. p = p->next;
  114. }
  115. }*/
  116. //在0号位置插入999
  117. insert(head, 0, 999);
  118. //遍历链表
  119. cout << "排序结果:" << endl;
  120. track(head);
  121. return 0;
  122. }

本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号