Phoenix_x

sort list

Apr 4th, 2018
287
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.19 KB | None | 0 0
  1. #include "stdafx.h"
  2. #include <iostream>
  3. using namespace std;
  4.  
  5. struct elem
  6. {
  7.     int key;
  8.     elem *next;
  9. }*start;
  10.  
  11.  
  12. void init();
  13. void add(int n);
  14. void print_list();
  15. void sort();
  16.  
  17. void main()
  18. {
  19.     init();
  20.     cout << "Vavedete chisla za spisaka (0 za kraj): " << endl;
  21.     int number;
  22.  
  23.     while (true)
  24.     {
  25.         cin >> number;
  26.  
  27.         if (number == 0)
  28.         {
  29.             break;
  30.         }
  31.  
  32.         add(number);
  33.     }
  34.  
  35.     sort();
  36.     print_list();
  37. }
  38.  
  39. void init()
  40. {
  41.     start = NULL;
  42. }
  43.  
  44. void add(int n)
  45. {
  46.     elem *p = start, *q;
  47.     q = new elem;
  48.     q->key = n;
  49.     q->next = NULL;
  50.     if (start)
  51.     {
  52.         while (p->next)
  53.             p = p->next;
  54.         p->next = q;
  55.     }
  56.     else
  57.     {
  58.         start = q;
  59.     }
  60. }
  61.  
  62. void print_list()
  63. {
  64.     elem *p = start;
  65.  
  66.     if (start)
  67.     {
  68.         cout << "Elementite na spisaka sa: \n";
  69.  
  70.         while (p)
  71.         {
  72.             if (p->key != NULL) {
  73.                 cout << p->key << "\t";
  74.             }
  75.             p = p->next;
  76.         }
  77.         cout << endl;
  78.     }
  79.     else
  80.         cout << "Nqma elementi v spisaka.";
  81. }
  82.  
  83. void sort()
  84. {
  85.     elem *p1 = start;
  86.  
  87.     while (p1 != NULL)
  88.     {
  89.         elem *p2 = p1;
  90.  
  91.         while (p2 != NULL)
  92.         {
  93.             if (p1->key > p2->key)
  94.             {
  95.                 int swap = p1->key;
  96.                 p1->key = p2->key;
  97.                 p2->key = swap;
  98.             }
  99.  
  100.             p2 = p2->next;
  101.         }
  102.         p1 = p1->next;
  103.     }
  104. }
Advertisement
Add Comment
Please, Sign In to add comment