Spicke

spisok vstavki

May 20th, 2017
161
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.11 KB | None | 0 0
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. #include <windows.h>
  4. #include <iostream>
  5.  
  6. using namespace std;
  7.  
  8. struct list
  9. {
  10.     int data;
  11.     struct list *next;
  12. };
  13.  
  14. struct list * insert( struct list *node, int data )
  15. {
  16.     struct list *tmp = (struct list*)malloc( sizeof( struct list ) );
  17.  
  18.     if ( tmp != NULL )
  19.     {
  20.         tmp->data = data;
  21.  
  22.         if ( node != NULL )
  23.         {
  24.             tmp->next = node->next;
  25.             node->next = tmp;
  26.         }
  27.         else
  28.         {
  29.             tmp->next = NULL;
  30.         }
  31.     }
  32.  
  33.     return tmp;
  34. }
  35.  
  36. void display( struct list *node )
  37. {
  38.     for ( ; node != NULL; node = node->next ) printf( "%d ", node->data );
  39. }
  40.  
  41. struct list * clear( struct list *node )
  42. {
  43.     while ( node != NULL )
  44.     {
  45.         struct list *tmp = node;
  46.         node = node->next;
  47.  
  48.         free( tmp );
  49.     }
  50.  
  51.     return node;
  52. }
  53.  
  54. struct list * sort( struct list *root )
  55. {
  56.     struct list *new_root = NULL;
  57.  
  58.     while ( root != NULL )
  59.     {
  60.         struct list *node = root;
  61.         root = root->next;
  62.  
  63.         if ( new_root == NULL || node->data < new_root->data )
  64.         {
  65.             node->next = new_root;
  66.             new_root = node;
  67.         }
  68.         else
  69.         {
  70.             struct list *current = new_root;
  71.             while ( current->next != NULL && !( node->data < current->next->data ) )
  72.             {                  
  73.                   current = current->next;
  74.             }                
  75.  
  76.             node->next = current->next;
  77.             current->next = node;
  78.         }
  79.     }
  80.  
  81.     return new_root;
  82. }
  83.  
  84.  
  85.  
  86. int main()
  87. {
  88.     setlocale(LC_ALL, "Rus");
  89.     int N;
  90.     cout << "Введите размер списка:  "; cin >> N;
  91.     int *a;
  92.     a = new int[N];
  93.     for (int i = 0; i < N; i++) a[i] = rand() % 10;
  94.     struct list *root = NULL;
  95.     struct list **tmp = &root;
  96.  
  97.     for ( size_t i = 0; i < N; i++ )
  98.     {
  99.         *tmp = insert( *tmp, a[i] );
  100.         tmp = &( *tmp )->next;
  101.     }
  102.  
  103.     display( root );
  104.     printf( "\n" );
  105.  
  106.     root = sort( root );
  107.  
  108.     display( root );
  109.     printf( "\n" );
  110.  
  111.     root = clear( root );
  112. }
Advertisement
Add Comment
Please, Sign In to add comment