user379888
user379888

Reputation:

sorting the linked list

I am trying to make a function that sorts the linked list,which sorts the list by names.

struct student
 {
  char name[50];
  int roll_no;
  struct student *ptr_next;
 }*ptr_this,*ptr_first;/*ptr first points to first pointer */
void SortRecord(void)
{
 struct student *out,*in,*temp;
 for(out=ptr_first;out!=(struct student*)NULL;out=out->ptr_next)
 {
  for(in=out->ptr_next;out->ptr_next!=(struct student*)NULL;in=in->ptr_next)
  {
   if(strcmpi(out->name,in->name)<0)

  temp->ptr_next=in->ptr_next;
  in->ptr_next=out->ptr_next;
  out->ptr_next=temp->ptr_next;/*The program stops at this instant and does not proceed after this line*/
  }
 }
 printf("Records have been successfully sorted.");

I am stuck with 2 questions: EDIT: I understood that we only need to swap the pointers not the contents but my code still hangs at the swapping at the place mentioned above.

Upvotes: 0

Views: 517

Answers (5)

Ishtar
Ishtar

Reputation: 11662

Do you really mean this?

if(strcmpi(out->name,in->name)<0)
  temp->ptr_next=in->ptr_next;

in->ptr_next=out->ptr_next;
out->ptr_next=temp->ptr_next;

Or do you want this?

if(strcmpi(out->name,in->name)<0)
{
  temp->ptr_next=in->ptr_next;
  in->ptr_next=out->ptr_next;
  out->ptr_next=temp->ptr_next;
}

I think you tried to dereference temp and temp could be uninitialized (struct student *out,*in,*temp;). Try using a debugger!

Upvotes: 1

Christoffer
Christoffer

Reputation: 12910

If you know that the result needs to be sorted, try sorting on list insertion instead. Depending on your design requirements, a heavy insert might be tolerated given that the "sorting" step becomes redundant. The concept might also be a bit easier to grasp.

Upvotes: 2

pejotr
pejotr

Reputation: 120

Hey, i think you should draw list and pointer on the piece of paper and analyze it

*temp=*in; *in=*out; 
*out=*temp; 
temp->ptr_next=in->ptr_next;

After executing these lines temp->ptr_next == temp :)

Upvotes: 1

Eric Fortin
Eric Fortin

Reputation: 7603

In a sort of a linked list, you should only have to move the ptr_next anyway. I don't know why you're doing member copy with

*temp=*in;
*in=*out;
*out=*temp;

This way, you won't have problem with the null ptr_next since you'll be swapping them and only the last node will ever points to NULL which is right.

Upvotes: 1

aJ.
aJ.

Reputation: 35460

Do you really want to sort the links as well? You can try by swapping the name and rollno during sort---

1,a->2,m->3,p->4,d
 ==> sort the names ... 
     inner loop (swap the roll no and names, leave pointers as it is.... )

Upvotes: 0

Related Questions