hello people, I have a problem in sorting linked list according to id number of student in secondary school system ,the code is not working .can any body help me please ?!!
Here Is my code.

void sortbyID()
{
   
   struct school *pre;
   struct school *move;
   

   move=head;
   pre=move;
   move=move->next;
   
   

   while (pre!=NULL && move!=NULL)
   {
	   if ((pre->id)>=(move->id))
	   {
		   move=pre;
		   pre=pre->next;
	   }

	   { pre=pre->next;
	   } move=move->next;

   
   }


getch();


}
kvprajapati commented: Donot open too many threads for single question. -1

Recommended Answers

All 4 Replies

You cannot swap two nodes of linked list just by holding two pointers you need at least three for totally swapping two nodes so instead why not switch the contents instead of nodes ???

void sortbyID()
{ 

     struct school *pre;
     struct school *move;
     struct school *temp;
    /*And allocate memory for temp here because we need to use it ahead*/

    /*I hope head is declared globally or else you need to pass it to this function*/
     move=head;
     pre=head;
     move=move->next;

    /*How can pre be equal to NULL??? Its before move right???*/
    while (move!=NULL)
    {
          if ((pre->id)>(move->id))/*Why to move if they are equal?*/
         {
            /*Just move the contents*/
            temp->id=pre->id;
            pre->id=move->id;
            move->id=temp->id;
         }
          pre=pre->next;
          move=move->next;
   }


   /*Free temp we don't need it anymore*/
   free(temp);
   getch(); /*You don't really need it*/
}

The code is still not working .I don't know what's wrong.
Thanks anyway...

You must have messed up something in other parts of the program... go through it step by step as if you were compiling it...k be the compiler for a while and you'll see the mistakes on your own...;)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.