开发者

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.


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.


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.


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 :)


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!


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.... )
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜