I created a program to sort double linked list in ascending order, and the result was unexpected, but when I used the same program for descending order by changing a line in it, it worked perfectly. Please tell where m going wrong
/*Structure of double linked list */
struct dlink
{
int num;
struct dlink *plink; //previous address
struct dlink *nlink; //next address
};
void main()
{
clrscr();
struct dlink *st;
st=NULL;
append(&st,100); //to put values in double linked list
append(&st,32);
append(&st,200);
append(&st,107);
display(st);
ascending(&st);
display(st);
getch();
}
/* function to add values to double linked list */
void append(struct dlink **q,int n)
{
struct dlink *temp,*r;
temp=*q;
if(temp==NULL)
{
temp=(dlink *)malloc(sizeof(dlink));
temp->num=n;
temp->plink=NULL;
temp->nlink=NULL;
*q=temp;
}
else
{
while(temp->nlink!=NULL)
temp=temp->nlink;
r=(dlink *)malloc(sizeof(dlink));
r->num=n;
r->nlink=NULL;
r->plink=temp;
temp->nlink=r;
}
}
void ascending(struct dlink **q)
{
struct dlink *temp,*s,*p=NULL;
temp=*q;
int a=count(*q);
printf(" a %d ",a);
for(int i=0;i<a;i++,temp=temp->nlink)
{
s=temp->nlink;
for(int j=i+1;j<=a;j++,s=s->nlink)
{
if((temp->num) < (s->num)) //for ascending i was using //if(temp->num > s->num but it is not getting desired result it is just printing //one value and by this one for descending order program is working perfectly //for descending order
{
(s->plink)->nlink=s->nlink;
if(s->nlink!=NULL)
(s->nlink)->plink=s->plink;
s->plink=temp->plink;
s->nlink=temp;
temp=s;
(temp->nlink)->plink=temp;
}
}
if(i==0)
*q=temp;
if(i!=0)
{
p->nlink=temp;
temp->plink=p;
}
p=temp;
}
temp=*q;
/* To see if the addresse , previous address , next address are correct */
while(temp!=NULL)
{
printf("as %u %u %u\n",temp->plink,temp->nlink,temp);
temp=temp->nlink;
}
}