Advertisement
AleksandarH

Y1S2 Sort Linked List in Ascending Order Homework

May 21st, 2021
384
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.82 KB | None | 0 0
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. struct elem {
  5.     int key;
  6.     struct elem* next;
  7. } *start;
  8.  
  9. void init() {
  10.     start = NULL;
  11. }
  12.  
  13. struct elem* swap(struct elem* p, struct elem* q) {
  14.     struct elem* tmp = q->next;
  15.     q->next = p;
  16.     p->next = tmp;
  17.     return q;
  18. }
  19.  
  20. int sort(struct elem** start, int list_size) {
  21.     struct elem** s;
  22.     int i, j, swapped = 0;
  23.     for (i = 0; i <= list_size; i++) {
  24.         s = start;
  25.         for (j = 0; j < list_size - i - 1; j++) {
  26.             struct elem* p = *s;
  27.             struct elem* q = p->next;
  28.             if (p->key < q->key) {
  29.                 *s = swap(p, q);
  30.                 swapped = 1;
  31.             }
  32.             s = &(*s)->next;
  33.         }
  34.         if (swapped == 0)
  35.             break;
  36.     }
  37.     return 0;
  38. }
  39.  
  40. void add_b(int n) {
  41.     elem* p = start;
  42.     start = new elem;
  43.     start->key = n;
  44.     start->next = p;
  45. }
  46.  
  47. void add_e(int n) {
  48.     elem* p = start, * q = start;
  49.     q = new elem;
  50.     q->key = n;
  51.     q->next = NULL;
  52.     if (start) {
  53.         while (p->next)
  54.             p = p->next;
  55.         p->next = q;
  56.     }
  57.     else
  58.         start = q;
  59. }
  60.  
  61. void output(struct elem* n) {
  62.     while (n != NULL) {
  63.         cout << n->key << "  |  ";
  64.         n = n->next;
  65.     }
  66.     cout << endl;
  67. }
  68.  
  69. int main() {
  70.     init();
  71.     int n, x, i = 0;
  72.  
  73.     cout << " > Enter key value for start element |  ";
  74.     cin >> n;
  75.     add_b(n);
  76.     i++;
  77.  
  78.     cout << " > Enter how many elements to add after start |  ";
  79.     cin >> x;
  80.     for (int j = 0; j < x; j++) {
  81.         cout << " > Enter key value for element " << i << " |  ";
  82.         cin >> n;
  83.         add_e(n);
  84.         i++;
  85.     }
  86.  
  87.     cout << " > List before sort |  ";
  88.     output(start);
  89.  
  90.     sort(&start, i);
  91.  
  92.     cout << " > List after sort |  ";
  93.     output(start);
  94.  
  95.     return 0;
  96. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement