#include<stdio.h>
#include<stdlib.h>
#include<stddef.h>
#define DEFNELEMENTS 500
struct node
{
int value;
struct node *next;
};
struct node* GenerateNumbers(int, struct node*);
struct node* InsertionSort(struct node*);
void PrintList(struct node*);
int main(int argc, char *argv[])
{
int NofElements;
struct node *head;
if(argc == 2)
NofElements = atoi(argv[1]);
else
NofElements = DEFNELEMENTS;
head = GenerateNumbers(NofElements, head);
PrintList(head);
head = InsertionSort(head);
PrintList(head);
char c;
c = getchar();
return(0);
}
struct node* GenerateNumbers(int NElements, struct node *head)
{
struct node *temp;
int count;
temp = (struct node*) malloc((int)sizeof(struct node));
head = temp;
for(count=0; count<NElements; count++)
{
temp->value = rand();
temp->next = (struct node*) malloc(sizeof(struct node));
temp = temp->next;
}
temp->value = '';
temp->next=NULL;
return(head);
}
struct node* InsertionSort(struct node *head)
{
struct node *tempout;
struct node *tempin;
struct node *tempoutpre = NULL;
struct node *tempinpre = NULL;
for(tempout=head; (tempout->value)!= ''; tempoutpre=tempout, tempout=tempout->next)
{
for(tempin=head; (tempin->value)<=(tempout->value) && (tempin->next)!=(tempout->next); tempinpre=tempin, tempin=tempin->next);
if((tempin->next)!=(tempout->next))
{
tempoutpre->next = tempout->next;
tempout->next = tempin;
if(tempin == head)
head = tempout;
else
tempinpre->next = tempout;
}
}
return(head);
}
void PrintList(struct node *head)
{
struct node *temp;
for(temp=head; (temp->value)!=''; temp=temp->next)
{
printf("%6d ",temp->value);
}
printf("\n");
}
12.956033
77.656476