fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. struct Elem
  5. {
  6. int num;
  7. Elem* next;
  8. };
  9.  
  10. void printLinkedList(Elem* list) {
  11. while (list) {
  12. cout << list->num << ' ';
  13. list = list->next;
  14. }
  15. cout << endl;
  16. }
  17.  
  18. bool deleteFromLinkedList(Elem* &list) {
  19.  
  20. if (!list)
  21. return false;
  22.  
  23. Elem *curr = list, *next = list->next, *prev = NULL;
  24. bool anyRemoved = false;
  25.  
  26. while (next)
  27. {
  28. if (curr->num < next->num) {
  29. if (prev)
  30. prev->next = next;
  31. else
  32. list = next;
  33. delete curr;
  34. anyRemoved = true;
  35. }
  36. else {
  37. prev = curr;
  38. }
  39. curr = next;
  40. next = curr->next;
  41. }
  42.  
  43. return anyRemoved;
  44. }
  45.  
  46. int main()
  47. {
  48. Elem* first = NULL, *last = NULL, *p;
  49. int i;
  50.  
  51. //cout << "Enter any number or 0 to finish: ";
  52. cin >> i;
  53.  
  54. while (i != 0)
  55. {
  56. p = new Elem;
  57. p->num = i;
  58. p->next = NULL;
  59. if (first == NULL)
  60. {
  61. first = last = p;
  62. }
  63. else
  64. {
  65. last->next = p;
  66. last = last->next;
  67. }
  68. //cout << "Enter any number or 0 to finish: ";
  69. cin >> i;
  70. }
  71.  
  72. printLinkedList(first);
  73. while (deleteFromLinkedList(first));
  74. printLinkedList(first);
  75. }
Success #stdin #stdout 0.01s 5388KB
stdin
9 8 7 12 11 6 0
stdout
9 8 7 12 11 6 
12 11 6