简体   繁体   English

排序链表

[英]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. 这个概念可能也更容易掌握。

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 :) 执行这些行之后, temp->ptr_next == temp :)

In a sort of a linked list, you should only have to move the ptr_next anyway. 在某种链表中,无论如何您只需要移动ptr_next。 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. 这样,您将不会对null ptr_next产生任何问题,因为您将交换它们,并且只有最后一个节点会指向正确的NULL。

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; ). 我认为您尝试取消引用temptemp可能未初始化( 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--- 您可以在排序时通过交换名称和rollno来尝试-

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM