当前位置:   article > 正文

编写在非递减有序链表中插入一个元素(整型),使链表元素仍有序的函数(必须采用函数实现,否则不算成绩),并利用该函数建立一个非递减有序单向链表,之后输出这个有序的单链表。_建立一个非递减有序单链表(不少于5个元素结点),输出该链表中重复的元素以及重复次

建立一个非递减有序单链表(不少于5个元素结点),输出该链表中重复的元素以及重复次
  1. #include <iostream>
  2. using namespace std;
  3. typedef struct list
  4. {
  5. int data;
  6. struct list * pNext;
  7. } List, *pList;
  8. pList CreatHeadNode ();
  9. pList CreatNewNode ();
  10. void BuildList (pList);
  11. void PrintList (pList);
  12. void SortList (pList);
  13. int main ()
  14. {
  15. int n;
  16. pList pHead = CreatHeadNode ();
  17. BuildList (pHead);
  18. SortList (pHead);
  19. PrintList (pHead);
  20. }
  21. pList CreatHeadNode ()
  22. {
  23. pList pNewNode = new List;
  24. if (pNewNode == NULL)
  25. exit (-1);
  26. pNewNode->data = 0;
  27. pNewNode->pNext = NULL;
  28. return pNewNode;
  29. }
  30. pList CreatNewNode ()
  31. {
  32. pList pNewNode = new List;
  33. if (pNewNode == NULL)
  34. exit (-1);
  35. pNewNode->pNext = NULL;
  36. cin >> pNewNode->data;
  37. if (pNewNode->data == 0)
  38. return NULL;
  39. return pNewNode;
  40. }
  41. void BuildList (pList pHead)
  42. {
  43. pList pTail = pHead;
  44. pList pNewNode = CreatNewNode ();
  45. while (pNewNode)
  46. {
  47. pTail->pNext = pNewNode;
  48. pTail = pNewNode;
  49. pNewNode = CreatNewNode ();
  50. }
  51. }
  52. void PrintList (pList pHead)
  53. {
  54. pList p = pHead->pNext;
  55. while (p)
  56. {
  57. cout << p->data << " ";
  58. p = p->pNext;
  59. }
  60. }
  61. void SortList (pList pHead)
  62. {
  63. pList p = pHead->pNext;
  64. pList q = p->pNext;
  65. int t;
  66. while (p)
  67. {
  68. q = p->pNext;
  69. while (q)
  70. {
  71. if (p->data > q->data)
  72. {
  73. t = p->data;
  74. p->data = q->data;
  75. q->data = t;
  76. }
  77. q = q->pNext;
  78. }
  79. p = p->pNext;
  80. }
  81. }

本文内容由网友自发贡献,转载请注明出处:https://www.wpsshop.cn/w/从前慢现在也慢/article/detail/858793
推荐阅读
相关标签
  

闽ICP备14008679号