makrusak

List with sort and delete_min

Dec 12th, 2013
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.71 KB | None | 0 0
  1. // I love Nastya :)
  2. #include <iostream>
  3. using namespace std;
  4. struct LIST
  5. {
  6.         int val;
  7.         LIST * next;
  8. };
  9. LIST *read (LIST *head, int x)
  10. {
  11.   LIST *pv =new LIST;
  12.   pv->val=x;
  13.   pv->next=head;
  14.   head=pv;
  15.   return head;
  16. }
  17. void print (LIST * list1)
  18. {
  19.   for (LIST *a = list1; a; a = a->next) cout << a->val << " ";
  20.   cout << "\n";
  21. }
  22. LIST * Sort (LIST *list)
  23. {
  24.   LIST *reslist = NULL;
  25.   LIST *next = NULL;
  26.   for (LIST *a = list; a; a = next) {
  27.     next = a->next;
  28.     a->next = NULL;
  29.     if (reslist==NULL) {
  30.       reslist = a;
  31.     }
  32.     else if (reslist->val >= a->val) {
  33.       a->next = reslist;
  34.       reslist = a;
  35.     }
  36.     else {
  37.       LIST* to = reslist;
  38.       while ( !(to->next==NULL || to->next->val >= a->val ))
  39.         to = to->next;
  40.       a->next = to->next;
  41.       to->next = a;
  42.     }
  43.   }
  44.   return reslist;
  45. }
  46.  
  47. LIST * delete_min(LIST *list) {
  48.   int mi = 2*1000*1000*1000;
  49.   for (LIST *a = list; a; a = a->next) {
  50.     if (a->val < mi) mi = a->val;
  51.   }
  52.   if (list->val == mi) {
  53.     LIST *ret = list->next;
  54.     delete list;
  55.     return ret;
  56.   }
  57.   bool deleted = false;
  58.   for (LIST *a = list; !deleted && a->next; a = a->next) {
  59.     LIST *s = a->next;
  60.     if (s->val == mi) {
  61.       a->next = s->next;
  62.       delete s;
  63.       deleted = true;
  64.     }
  65.   }
  66.   return list;
  67. }
  68.  
  69.  
  70.  
  71.  
  72. int main ()
  73. {
  74.     LIST * list1 = NULL;
  75.     int n, data;
  76.     cout << "Enter size of the list: ";
  77.     cin >> n;
  78.     for (int i=0; i<n; i++)
  79.     {
  80.         cin >> data;
  81.         list1=read (list1, data);
  82.     }
  83.     print(list1);
  84.     list1 = delete_min(list1);
  85.     print(list1);
  86.     list1 = Sort(list1);
  87.     print(list1);
  88.     list1 = delete_min(list1);
  89.     print(list1);
  90.     return 0;
  91. }
Advertisement
Add Comment
Please, Sign In to add comment