Saturday, 16 February 2013


After doing some basic append and display in linked list lets try to insert nodes in sorted order in the linked list.Here's the code for that.The code is very much similar to the 1st code except that here in append function we check  the value to be inserted should be on which position in linked list so that when we display the linked list it remains sorted.
//Lets do something more challenging...
#include<stdio.h>
#include<stdlib.h>

struct node
{
int data;
struct node *next;
};

void append_sort(struct node **,int);
void display(struct node *);
int main()
{
struct node *start=NULL;
append_sort(&start,15);
append_sort(&start,10);
append_sort(&start,25);
append_sort(&start,5);
append_sort(&start,16);
append_sort(&start,22);
append_sort(&start,24);
append_sort(&start,8);
append_sort(&start,31);
append_sort(&start,12);
display(start);
return 0;
}

void append_sort(struct node **ps,int x)
{
struct node *temp,*temp1,*q;
temp1=(struct node *)malloc(sizeof(struct node));
temp1->data=x;
if(*ps==NULL)
{
*ps=temp1;
(*ps)->next=NULL;
return;
}
temp=*ps;
if(temp->data>x)
{
*ps=temp1;
(*ps)->next=temp;
return;
}
while(temp->next!=NULL && temp->data<x)
{
q=temp;
temp=temp->next;
}
if(temp->data<x)
{
temp1->next=NULL;
temp->next=temp1;
}
else
{
q->next=temp1;
temp1->next=temp;
}
}

void display(struct node *ps)
{
while(ps!=NULL)
{
printf("%d\n",ps->data);
ps=ps->next;
}
}

No comments:

Post a Comment