fork download
  1. #include <iostream>
  2. #include <string>
  3. using namespace std;
  4.  
  5. struct Sterminarz
  6. {
  7. Sterminarz *next = NULL;
  8. int year;
  9. int month;
  10. int day;
  11. int hour;
  12. string note;
  13.  
  14. bool operator<(const Sterminarz &rhs) const {
  15. if (year < rhs.year) return true;
  16. if (year > rhs.year) return false;
  17.  
  18. if (month < rhs.month) return true;
  19. if (month > rhs.month) return false;
  20.  
  21. if (day < rhs.day) return true;
  22. if (day > rhs.day) return false;
  23.  
  24. return (hour < rhs.hour);
  25.  
  26. /* alternatively:
  27. return std::tie(year, month, day, hour) < std::tie(rhs.year, rhs.month, rhs.day, rhs.hour);
  28. */
  29. }
  30. };
  31.  
  32. Sterminarz* add(Sterminarz* &head, int year, int month, int day, int hour, string note)
  33. {
  34. Sterminarz **p = &head;
  35. while (*p)
  36. p = &((*p)->next);
  37.  
  38. *p = new Sterminarz;
  39. (*p)->year = year;
  40. (*p)->month = month;
  41. (*p)->day = day;
  42. (*p)->hour = hour;
  43. (*p)->note = note;
  44.  
  45. return *p;
  46. }
  47.  
  48. Sterminarz* findEarliest(Sterminarz *head, Sterminarz** beforeEarliest)
  49. {
  50. if (beforeEarliest)
  51. *beforeEarliest = NULL;
  52.  
  53. if (!head)
  54. return NULL;
  55.  
  56. Sterminarz *p, *previous = head, *earliest = head;
  57. int counter = 0;
  58.  
  59. for(p = head->next; p; p = p->next)
  60. {
  61. if (*p < *earliest)
  62. {
  63. earliest = p;
  64. if (beforeEarliest) *beforeEarliest = previous;
  65. counter++;
  66. //printNote(earliest, counter);
  67. }
  68. previous = p;
  69. }
  70.  
  71. return earliest;
  72. }
  73.  
  74. void printList(Sterminarz *head)
  75. {
  76. while (head) {
  77. cout << head->note << " ";
  78. head = head->next;
  79. }
  80. }
  81.  
  82. void clearList(Sterminarz* &head)
  83. {
  84. while (head) {
  85. Sterminarz *next = head->next;
  86. delete head;
  87. head = next;
  88. }
  89. }
  90.  
  91. int main()
  92. {
  93. Sterminarz *head = NULL;
  94. Sterminarz *p = add(head, 2020, 5, 29, 12, "1");
  95. p = add(p, 2020, 5, 29, 6, "2");
  96. add(p, 2020, 1, 1, 10, "3");
  97.  
  98. cout << "before: ";
  99. printList(head);
  100. cout << endl;
  101.  
  102. Sterminarz *beforeEarliest;
  103. Sterminarz *earliest = findEarliest(head, &beforeEarliest);
  104. if (earliest != head)
  105. {
  106. beforeEarliest->next = earliest->next;
  107. earliest->next = head;
  108. head = earliest;
  109. }
  110.  
  111. cout << "after: ";
  112. printList(head);
  113. cout << endl;
  114.  
  115. clearList(head);
  116.  
  117. return 0;
  118. }
Success #stdin #stdout 0s 4524KB
stdin
Standard input is empty
stdout
before: 1 2 3 
after: 3 1 2