Write a program that will sort a list of strings (names of person) enter by the user given the value of n names.
#include <stdlib.h>
#include <stdio.h>
struct list
{
char name[20];
struct list *next;
};
struct list * insert( struct list *node, char *name )
{
struct list *tmp = malloc( sizeof( struct list ) );
if ( tmp != NULL )
{
tmp->name = name;
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( "%s ", node->name );
}
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->name < new_root->name )
{
node->next = new_root;
new_root = node;
}
else
{
struct list *current = new_root;
while ( current->next != NULL && !( node->name < current->next->name ) )
{
current = current->next;
}
node->next = current->next;
current->next = node;
}
}
return new_root;
}
#define N 4
int main()
{
char names[N][20] = { "vasya", "petya", "kolya", "dima"};
struct list *root = NULL;
struct list **tmp = &root;
for ( size_t i = 0; i < N; i++ )
{
*tmp = insert( *tmp, names[i] );
tmp = &( *tmp )->next;
}
display( root );
printf( "\n" );
root = sort( root );
display( root );
printf( "\n" );
root = clear( root );
}
Comments
Leave a comment