C语言链表的创建与排序
来源:优易学  2011-2-17 10:37:19   【优易学:中国教育考试门户网】   资料下载   IT书店
  include<stdio.h>
  #include<stdlib.h>
  typedef struct struct {
  int value;
  struct struct *next;
  }ts;
  main()
  {
  #define n 9
  int a[n],i;
  ts *head,*p;
  ts *createlink(int *,int);
  void sort(ts **);
  randomize();
  for(i=0;i a=random(9);
  head=createlink(a,n);
  for(p=head;p;p=p->next)
  printf(\"%-2d\",p->value);
  putchar(\’\\n\’);
  sort(&head);
  for(p=head;p;p=p->next)
  printf(\"%-2d\",p->value);
  getchar();
  }
  void sort(ts **h) /* 选择排序算法 */
  {
  ts *h1,*p,*q,*r,*s;
  h1=p=(ts *)malloc(sizeof(ts));
  p->next=*h;
  while(p->next) {
  q=p->next;
  r=p;
  while(q->next) {
  if(q->next->valuenext->value)
  r=q;
  q=q->next;
  }
  if(r!=p) {
  s=r->next;
  r->next=s->next;
  s->next=p->next;
  p->next=s;
  }
  p=p->next;
  }
  *h=h1->next;
  free(h1);
  }
  ts *createlink(int *a,int n)
  {
  int i;
  ts *h,*p;
  h=null;
  for(i=n;i>0;i--) {
  p=(ts *)malloc(sizeof(ts));
  p->value=a[i-1];
  p->next=h;
  h=p;
  }
  return h;
  }

责任编辑:小草

文章搜索:
 相关文章
热点资讯
资讯快报
热门课程培训