I wanted to sort the elements in linked list in ascending order. I have written the following code:
void don(struct node *head)
{
struct node *god,*tmp=head,*current,*bak;
for(god=head;god->next!=NULL;god=god->next)
{
current=god->next;
for(bak->next=tmp;(bak->next)!=(god->next);bak=bak->next)
{
if((current->data)<(bak->next->data))
{
god->next=current->next;
current->next=god;
bak->next=current;
}
}
}
}
But its resulting into infinte loop.
Please help in correcting the code :) !
I want it to do it in this way
5-2-3-1-4
2-5-3-1-4
2-3-5-1-4
1-2-3-5-4
1-2-3-4-5
This statement
god->next=current->next;
breaks the first for() loop:
for(god=head;god->next!=NULL;god=god->next)
try this
void don(struct node *head)
{
struct node *god,*tmp=head,*current,*bak;
int data;
for(god=head;god->next!='\0';god=god->next)
{
current=god->next;
for(current;current->next!='\0';current=current->next)
{
if((current->data)<(god->data))
{
data=current->data;
current->data=god->data;
god->data=data;
}
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.