Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2159476
  • 博文数量: 556
  • 博客积分: 11457
  • 博客等级: 上将
  • 技术积分: 5973
  • 用 户 组: 普通用户
  • 注册时间: 2011-02-24 22:33
文章分类

全部博文(556)

文章存档

2013年(22)

2012年(74)

2011年(460)

分类: C/C++

2011-05-10 13:33:04

 

  1. /**编写一个程序,根据test_data[]数组中给定的整数序列建立一个单链表,
  2. 然后对该单链表进行排序(元素数值从大到小排列),最后显示排序后的结果
  3. **/

  4. /**算法思路
  5.  本程序由两个函数组成,create()函数用于根据数组的元素建立一个单链表;sort()函数对该链表进行排序,其原理是:
  6.  用p指针遍历所有结点,其前是已排序好的结点,其后是待排序的结点,从该链表中找出一个data值最小的结点并删除之,
  7.  将删除结点插入到p所指结点的后面。 采用两重循环完成排序工作,外层while判定是否还有待排序的结点,没有则退出循环,
  8.  排序工作完成,有待排序结点时,则执行循环体一次,进行排序。实现本题功能的程序如下:
  9. **/

  10. #include <stdio.h>
  11. #include <stdlib.h>
  12. typedef struct linknode
  13. {
  14.    int data;
  15.    struct linknode *next;
  16. }node;

  17. node *create(int a[],int n)
  18. {
  19.         node *h,*q;
  20.         for(h=NULL;n;n--)
  21.         {
  22.              q=(node*)malloc(sizeof(node));
  23.              q->data=a[n-1];
  24.              q->next=h;
  25.              h=q;
  26.         }
  27.         return h;
  28. }

  29. void sort(node **h)
  30. {
  31.    node *p,*q,*r,*s,*h1;
  32.    h1=p=(node*)malloc(sizeof(node));
  33.    p->next=*h;
  34.    while(p->next!=NULL)
  35.    {
  36.      q=p->next;
  37.      r=p;
  38.      while(q->next!=NULL)
  39.      {
  40.      if(q->next->data<r->next->data)
  41.          r=q;
  42.      q=q->next;
  43.      }
  44.        if(r!=p)
  45.      {
  46.          s=r->next;
  47.          r->next=s->next;
  48.          s->next=p->next;
  49.          p->next=s;
  50.      }
  51.         p=p->next;
  52.    }
  53. *h1->next;
  54. free(h1);
  55. }

  56. int test_data[]={5,9,3,1,2,7,8,6,4};

  57. main()
  58. {
  59.    node *h,*p;
  60.    h=create(test_data,sizeof(test_data)/sizeof(int));

  61.     printf("排序前:\n");
  62.     for(p=h;p;p=p->next)
  63.       printf("%2d",p->data);
  64.     printf("\n");
  65.     sort(&h);
  66.     printf("排序后:\n");
  67.     for(p=h;p;p=p->next)
  68.          printf("%2d",p->data);
  69.      printf("\n");
  70.      return 0;
  71. }

输出结果:

  1. 排序前:
  2. 5 9 3 1 2 7 8 6 4
  3. 排序后:
  4. 5 6 7 8 9

 

 

 

阅读(14742) | 评论(2) | 转发(0) |
给主人留下些什么吧!~~

云碁2015-08-20 16:34:04

compaq5030:void sort(node **h)函数的下面一句应该变成:*h=h1->next,这样结果就能显示完整。

*h1->next;

是的。你说的正确
你能说下 用链表 排序的好处吗???

回复 | 举报

compaq50302014-10-31 11:29:46

void sort(node **h)函数的下面一句应该变成:*h=h1->next,这样结果就能显示完整。

*h1->next;