#include
typedef struct slist{
int entry;
struct slist *next;
}NODE;
NODE *createNode(int item)
{
NODE *newNode=NULL;
newNode=(NODE *)malloc(sizeof(NODE));
newNode->next=NULL;
newNode->entry =item;
return newNode;
}
NODE *sort(NODE *head,int item)
{
NODE *newNode=NULL,*runNode=head,*prevNode=NULL;
newNode=createNode(item);
if(head==NULL)
return newNode;
else {
while(runNode->next != NULL && newNode->entry>runNode->entry)
{
prevNode=runNode;
runNode=runNode->next;
}
if(newNode->entry<=runNode->entry){
if(prevNode == NULL){
head=newNode;
head->next=runNode;
}
else{
newNode->next = runNode;
prevNode->next = newNode;
}
}
else{
runNode->next = newNode;
}
}
return head;
}
void displayNodes(NODE *head)
{
NODE *runNode=head;
while(runNode!=NULL)
{
printf("[%d]->",runNode->entry );
runNode=runNode->next;
}
printf("NULL\n");
}
void main(void)
{
int input;
NODE *head=NULL;
// insert head node
// head = sort(head,50);displayNodes(head);
// head = sort(head,40);displayNodes(head);
// head = sort(head,70);displayNodes(head);
// head = sort(head,30);displayNodes(head);
// head = sort(head,60);displayNodes(head);
// head = sort(head,90);displayNodes(head);
do{
printf("input data (if exit input = 999):");
scanf("%d",&input);
if(input!=999)
head=sort(head,input);
}while(input != 999);
displayNodes(head);
}
No comments:
Post a Comment