Saturday, May 21, 2016

WAP to create singly link list in sorted order

#include<stdio.h>
#include<conio.h>
struct node
{
int n;
struct node *next;
}*first=NULL,*temp,*temp1;
void insert(int x)
{
temp=(struct node*)malloc(sizeof(struct node));
temp->n=x;
if(first==NULL)
{
temp->next=NULL;
first=temp;
}
else
{
temp1=first;
while(temp1->next->n<x && temp1->next!=NULL)
{
temp1=temp1->next;
}
if(temp1==first && temp1->n>x)
{
temp->next=first;
first=temp;
}
else
{
temp->next=temp1->next;
temp1->next=temp;
}
}
}
void display()
{
if(first==NULL)
{
printf("Stack is empty");
return;
}
temp=first;
while(temp!=NULL)
{
printf("\n%d",temp->n);
temp=temp->next;
}
}
void main()
{
int x;
char ch;
clrscr();
do
{
printf("\nEnter a value: ");
scanf("%d",&x);
insert(x);
fflush(stdin);
display();
printf("\nDo you want to contiune(Y/N):");
scanf("%c",&ch);

}while(ch=='y' || ch=='Y');
display();
getch();
}

No comments:

Post a Comment