Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdlib.h>
- #include <stdio.h>
- #include <windows.h>
- #include <iostream>
- using namespace std;
- struct list
- {
- int data;
- struct list *next;
- };
- struct list * insert( struct list *node, int data )
- {
- struct list *tmp = (struct list*)malloc( sizeof( struct list ) );
- if ( tmp != NULL )
- {
- tmp->data = data;
- if ( node != NULL )
- {
- tmp->next = node->next;
- node->next = tmp;
- }
- else
- {
- tmp->next = NULL;
- }
- }
- return tmp;
- }
- void display( struct list *node )
- {
- for ( ; node != NULL; node = node->next ) printf( "%d ", node->data );
- }
- struct list * clear( struct list *node )
- {
- while ( node != NULL )
- {
- struct list *tmp = node;
- node = node->next;
- free( tmp );
- }
- return node;
- }
- struct list * sort( struct list *root )
- {
- struct list *new_root = NULL;
- while ( root != NULL )
- {
- struct list *node = root;
- root = root->next;
- if ( new_root == NULL || node->data < new_root->data )
- {
- node->next = new_root;
- new_root = node;
- }
- else
- {
- struct list *current = new_root;
- while ( current->next != NULL && !( node->data < current->next->data ) )
- {
- current = current->next;
- }
- node->next = current->next;
- current->next = node;
- }
- }
- return new_root;
- }
- int main()
- {
- setlocale(LC_ALL, "Rus");
- int N;
- cout << "Введите размер списка: "; cin >> N;
- int *a;
- a = new int[N];
- for (int i = 0; i < N; i++) a[i] = rand() % 10;
- struct list *root = NULL;
- struct list **tmp = &root;
- for ( size_t i = 0; i < N; i++ )
- {
- *tmp = insert( *tmp, a[i] );
- tmp = &( *tmp )->next;
- }
- display( root );
- printf( "\n" );
- root = sort( root );
- display( root );
- printf( "\n" );
- root = clear( root );
- }
Advertisement
Add Comment
Please, Sign In to add comment