对链表进行排序
我正在尝试创建一个对链接列表进行排序的函数,该函数按名称对列表进行排序。
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 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果您知道需要对结果进行排序,请尝试对列表插入进行排序。根据您的设计要求,考虑到“排序”步骤变得多余,可能可以容忍重型插入。这个概念也可能更容易理解。
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.
在某种链表中,无论如何,您只需要移动 ptr_next 即可。我不知道你为什么用
这种方式进行成员复制,你不会遇到 null ptr_next 的问题,因为你将交换它们,并且只有最后一个节点会指向 NULL,这是正确的。
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
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.
嘿,我认为你应该在纸上绘制列表和指针并分析它
执行这些行后
temp->ptr_next == temp
:)Hey, i think you should draw list and pointer on the piece of paper and analyze it
After executing these lines
temp->ptr_next == temp
:)你真的是这个意思吗?
或者你想要这个吗?
我认为您尝试取消引用
temp
并且temp
可能未初始化(struct Student *out,*in,*temp;
)。尝试使用调试器!Do you really mean this?
Or do you want this?
I think you tried to dereference
temp
andtemp
could be uninitialized (struct student *out,*in,*temp;
). Try using a debugger!您真的想对链接进行排序吗?您可以尝试在排序时交换名称和rollno---
Do you really want to sort the links as well? You can try by swapping the name and rollno during sort---