c - 在c中对链表一一排序
问题描述
所以,我正在尝试对我的链接列表进行排序,但是似乎存在一些问题。所以基本上我的清单是这样的
3 6 9 7
5 3 4 6
2 4 1 6
我想对第二条垂直线进行排序。升序排序后的第二行应该是这样的
5 3 4 6
2 4 1 6
3 6 9 7
但是我的代码只对第二条垂直线进行排序,并且由于某种原因不会更改其他行,我该如何解决这个问题?
3 3 9 7
5 4 4 6
2 6 1 6
这是我的排序代码
void sort(struct node **h)
{
int i,j,a;
struct node *temp1;
struct node *temp2;
for(temp1=*h;temp1!=NULL;temp1=temp1->next)
{
for(temp2=temp1->next;temp2!=NULL;temp2=temp2->next)
{
if(temp2->num1 < temp1->num1)
{
a = temp1->num1;
temp1->num1 = temp2->num1;
temp2->num1 = a;
}
}
}
}
这也是我的打印功能
void printList(struct node *list) {
//start from the beginning
while(list != NULL) {
printf(" %d %d %d %d \n",list->data, list->num1,list->num2, list->num3);
list = list->next;
}
}
解决方案
有两种方法可以交换链表中的项目。
- 保留节点但替换所有数据
- 在指针本身之间交换
在您的解决方案中,您尝试交换数据,但只更改了结构的一个成员。您需要对 、 和 执行相同data
的num2
操作num3
。
推荐阅读
- r - 使用 system.time() 计时 R 代码时出现“找不到对象”和“意外符号”错误
- c++ - Gradle c++ project : win32 dependencies not included
- visual-studio - (405) Visual Studio 2017 (NuGet) 包管理器不允许的方法
- .htaccess - 如何使用 mod_rewrite 将 url 查询字符串更改为斜线
- laravel - Laravel same route url but different route name in different domain not access why?
- php - sleep() 不会阻止最大执行时间
- qt - 从 Qt 安装程序中运行 .bat 命令时无法确定 java 版本
- sql-server - 存储过程 - 游标 - 为记录字段赋值并在游标末尾选择
- python - use redis and mongo alongside postgres in docker
- java - Oozie 作业失败 Mapr 6.x