c++ - 为什么我在链表中的排序功能(通过交换数据进行排序)不起作用
问题描述
当我运行此函数时,它会返回所有数字而不进行任何排序?当我使用 for 循环时它工作得非常好?谁能告诉我哪里出错了?
struct node //structure node
{
int info;
struct node *link;
};
void sort(struct node *start) //function for sorting
{
struct node *p,*temp;
int r;
p = start;
temp = p->link;
while(p != NULL) //first loop
{
while(temp != NULL) //second loop
{
if(temp->info < p->info)
{
r=p->info;
p->info = temp->info;
temp->info = r;
}
temp = temp->link;
}
p = p->link;
}
}
解决方案
在外while
循环的第一次迭代之后,temp
将是NULL
. 但是,temp
没有设置在内while
循环之外,因此它将保持NULL
. start->info
只有不是最小的数字才会改变。
将赋值temp = p->link
移到外部 while 循环中:
void sort(struct node *start)
{
struct node *p,*temp;
int r;
p = start;
while(p != NULL)
{
temp = p->link; // <-------
while(temp != NULL)
{
if(temp->info < p->info)
{
r=p->info;
p->info = temp->info;
temp->info = r;
}
temp = temp->link;
}
p = p->link;
}
}
推荐阅读
- css - 如何使用变换原点让 svg 元素从中心旋转?
- node.js - 返回错误:查询返回超过 10000 个结果
- javascript - 我的 javascript 无法读取带有 innerText 的 php 数据库 $row 插入的属性
- android - 如果我在 Jetpack Compose 中配置导航,如何设置顶部应用栏
- android - AndroidX 迁移后,ListView 未在 OnCreate/OnStart 上显示任何数据
- python - Python 术语:接口与协议
- python - 如何将项目附加到班级的列表中?
- c# - Linq Query 计数缓慢。SQL查询非常快。我究竟做错了什么?
- go - GKE 容器被“Memory cgroup out of memory”杀死,但监控、本地测试和 pprof 显示使用量远低于限制
- python - Tkinter 日历没有在正确的位置网格化