单链表冒泡排序
今天做链表排序有个误区,就是以为交换的时候要连next节点也交换,还要固定head节点,想了很久也没做出来,但是后来看网上的提示,才知道只要交换节点内的数据就可以了,根本不用交换next节点
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 | #include <stdio.h> #include <stdlib.h> struct node { int data; struct node *next; }; struct node *create_list( int a[], int len) { struct node *phead; struct node *ptr; struct node *pre; phead=( struct node *) malloc ( sizeof ( struct node)); int i=0; phead->data=a[i]; phead->next=NULL; ptr=phead->next; pre=phead; for (i=1;i<len;i++) { ptr=( struct node *) malloc ( sizeof ( struct node)); ptr->data=a[i]; ptr->next=NULL; pre->next=ptr; ptr=ptr->next; pre=pre->next; } return phead; } void print_list( struct node *phead) { struct node *ptr=phead; while (ptr != NULL) { printf ( "%d " ,ptr->data); ptr=ptr->next; } printf ( "\n" ); } struct node *bubble( struct node *phead, int len) { struct node *ptr,*next; int temp; for ( int i=0;i<len;i++) { ptr=phead; next=ptr->next; for ( int j=len-i-1;j>0;j--) { if (ptr->data > next->data) { temp=ptr->data; ptr->data=next->data; next->data=temp; } ptr=ptr->next; next=next->next; } } return phead; } int main() { int a[10]={ 5,3,6,8,9,6,5,4,2,7 }; struct node *phead; phead=create_list(a,10); print_list(phead); phead=bubble(phead,10); print_list(phead); } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· [AI/GPT/综述] AI Agent的设计模式综述