Q.) WRITE A PROGRAM TO INSERT A NODE IN THE LINK LIST IN SORTED ORDER.
SOLUTION..
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node* next;
}*head;
int main()
{
struct node *temp;
int num,i,item;
scanf("%d",&num);
//creation of link list//
for(i=0;i<num;i++)
{
scanf("%d",&item);
if(i==0)
{
head=malloc(sizeof(struct node));
head->data=item;
temp=head;
}
else
{
temp->next=malloc(sizeof(struct node));
temp->next->data=item;
temp=temp->next;
}
}
temp->next=NULL;
printf("number to be inserted");
scanf("%d",&item);
struct node *newnode;
newnode=malloc(sizeof(struct node));
newnode->data=item;
//insertnode(&head,&newnode);
struct node *currn;
//adjusting the new node in link list//
if(head==NULL||head->data>newnode->data)
{
newnode->next=head;
head=newnode;
}
else
{
currn=head;
while(currn->next!=NULL&&currn->next->data<newnode->data)
{
currn=currn->next;
}
newnode->next=currn->next;
currn->next=newnode;
}
temp=head;
//printing all nodes of link list//
while(temp!=NULL)
{
printf("%d ",temp->data);
temp=temp->next;
}
return 0;
}
No comments:
Post a Comment