049.基数排序

举报
C语言与CPP编程 发表于 2022/04/29 23:55:05 2022/04/29
【摘要】 #include "stdio.h"#include "conio.h"#include "stdlib.h"#define MAX 5typedef struct node{ int k; struct node *next;} *lnode;lnode my_input(int *d){ lnode head,temp,termi...

  
  1. #include "stdio.h"
  2. #include "conio.h"
  3. #include "stdlib.h"
  4. #define MAX 5
  5. typedef struct node
  6. { int k;
  7. struct node *next;
  8. } *lnode;
  9. lnode my_input(int *d)
  10. { lnode head,temp,terminal;
  11. char s[MAX+1];
  12. printf("Input the records ('0' to end input):\n");
  13. scanf("%s",s);
  14. head=NULL;
  15. *d=0;
  16. terminal=NULL;
  17. while(s[0]!='0')
  18. {
  19. temp=(lnode)malloc(sizeof(struct node));
  20. if (strlen(s)>*d)
  21. *d=strlen(s);
  22. temp->k=atoi(s);
  23. if (head==NULL)
  24. { head=temp;
  25. terminal=temp;
  26. }
  27. else
  28. {
  29. terminal->next=temp;
  30. terminal=temp;
  31. }
  32. scanf("%s",s);
  33. }
  34. terminal->next=NULL;
  35. return head;
  36. }
  37. void my_output(lnode h)
  38. {
  39. lnode t=h;
  40. printf("\n");
  41. while (h!=NULL)
  42. {
  43. printf("%d ",h->k);
  44. h=h->next;
  45. }
  46. h=t;
  47. /* getch(); */
  48. }
  49. lnode Radix_Sort(lnode head,int d)
  50. {
  51. lnode p,q,h,t;
  52. int i,j,x,radix=1;
  53. h=(lnode)malloc(10*sizeof(struct node));
  54. t=(lnode)malloc(10*sizeof(struct node));
  55. for (i=d;i>=1;i--)
  56. {
  57. for (j=0;j<=9;j++)
  58. { h[j].next=NULL;
  59. t[j].next=NULL;
  60. }
  61. p=head;
  62. while (p!=NULL)
  63. {
  64. x=((p->k)/radix)%10;
  65. if (h[x].next==NULL)
  66. {
  67. h[x].next=p;
  68. t[x].next=p;
  69. }
  70. else
  71. {
  72. q=t[x].next;
  73. q->next=p;
  74. t[x].next=p;
  75. }
  76. p=p->next;
  77. }
  78. j=0;
  79. while (h[j].next==NULL)
  80. j++;
  81. head=h[j].next;
  82. q=t[j].next;
  83. for (x=j+1;x<=9;x++)
  84. if (h[x].next!=NULL)
  85. {
  86. q->next=h[x].next;
  87. q=t[x].next;
  88. }
  89. q->next=NULL;
  90. radix*=10;
  91. printf("\n---------------------\n");
  92. }
  93. return head;
  94. }
  95. void my_free(lnode h)
  96. {
  97. lnode temp=h;
  98. while (temp)
  99. {
  100. h=temp->next;
  101. free(temp);
  102. temp=h;
  103. }
  104. }
  105. void main()
  106. {
  107. lnode h;
  108. int d;
  109. clrscr();
  110. h=my_input(&d);
  111. puts("The sequence you input is:");
  112. my_output(h);
  113. h=Radix_Sort(h,d);
  114. puts("\nThe sequence after radix_sort is:");
  115. my_output(h);
  116. my_free(h);
  117. puts("\n Press any key to quit...");
  118. getch();
  119. }

文章来源: blog.csdn.net,作者:程序员编程指南,版权归原作者所有,如需转载,请联系作者。

原文链接:blog.csdn.net/weixin_41055260/article/details/124491538

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。