fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. struct Linknode {
  5. int data;
  6. struct Linknode* next;
  7. };
  8.  
  9. void print(Linknode* header) {
  10. Linknode* pcurrent = header->next;
  11. while (pcurrent != NULL) {
  12. cout << pcurrent->data << " ";
  13. pcurrent = pcurrent->next;
  14. }
  15. cout << endl;
  16. }
  17.  
  18. int check(int n, Linknode* header) {
  19. Linknode* pcurrent = header->next;
  20. while (pcurrent != NULL) {
  21. if (pcurrent->data == n) {
  22. cout << "Duplicate entry, please re-enter." << endl;
  23. return 1;
  24. }
  25. pcurrent = pcurrent->next;
  26. }
  27. return 0;
  28. }
  29.  
  30. void exchange(int x, int y, Linknode* header) {
  31. if (x == y) return;
  32.  
  33. Linknode *px_prev = NULL, *px = header->next;
  34. Linknode *py_prev = NULL, *py = header->next;
  35.  
  36. // Find nodes and their previous nodes
  37. for (int i = 1; i < x && px != NULL; i++) {
  38. px_prev = px;
  39. px = px->next;
  40. }
  41. for (int i = 1; i < y && py != NULL; i++) {
  42. py_prev = py;
  43. py = py->next;
  44. }
  45.  
  46. if (px == NULL || py == NULL) return;
  47.  
  48. // Swap nodes
  49. if (px_prev != NULL) px_prev->next = py;
  50. else header->next = py;
  51.  
  52. if (py_prev != NULL) py_prev->next = px;
  53. else header->next = px;
  54.  
  55. Linknode* temp = px->next;
  56. px->next = py->next;
  57. py->next = temp;
  58. }
  59.  
  60. Linknode* create() {
  61. Linknode* header = new Linknode;
  62. header->data = -1;
  63. header->next = NULL;
  64. Linknode* tail = header;
  65. int val;
  66.  
  67. while (true) {
  68. cin >> val;
  69. if (val == 0) break;
  70. if (check(val, header)) continue;
  71.  
  72. Linknode* newnode = new Linknode;
  73. newnode->data = val;
  74. newnode->next = NULL;
  75. tail->next = newnode;
  76. tail = newnode;
  77. print(header);
  78. }
  79. return header;
  80. }
  81.  
  82. void sort(Linknode* header) {
  83. if (header == NULL || header->next == NULL) return;
  84.  
  85. Linknode *i, *j;
  86. for (i = header->next; i != NULL; i = i->next) {
  87. for (j = i->next; j != NULL; j = j->next) {
  88. if (i->data > j->data) {
  89. exchange(i->data, j->data, header);
  90. }
  91. }
  92. }
  93. }
  94.  
  95. int main() {
  96. char command;
  97. do {
  98. Linknode* header = create();
  99. sort(header);
  100. print(header);
  101.  
  102. cout << "Enter '@' to exit or any other key to continue: ";
  103. cin >> command;
  104. } while (command != '@');
  105.  
  106. return 0;
  107. }
  108.  
Success #stdin #stdout 0.01s 5276KB
stdin
3
5
7
6
12
4
8
0
@
stdout
3 
3 5 
3 5 7 
3 5 7 6 
3 5 7 6 12 
3 5 7 6 12 4 
3 5 7 6 12 4 8 
3 5 7 4 6 12 8 
Enter '@' to exit or any other key to continue: