数据结构有序表的创建与输出

来源:互联网 发布:淘宝k8分销平台可靠吗 编辑:程序博客网 时间:2024/06/05 21:50

数据结构有序表的创建与输出

//有序表

#include<stdio.h>

#include<stdlib.h>

typedef int Element;   //数据类型

typedef struct node{

       Element data;    //元素

       struct node * next;   //节点域

}SortList;

/*

创建列表(尾插法)

已知参数:初始化的列表 ;存了数据的数组,数组的长度  

*/

void CreateSortList(SortList *L, int a[], int n){ 

       int i;

       SortList *s,*r;

       r=L;

       for(i=0l;i<n;i++){

              s=(SortList*)malloc(sizeof(SortList));

              s->data=a[i];

              r->next=s;

              r=s;             

       }     

       r->next=NULL;

}

//排序

void sort(SortList   *L){

       SortList *p,*q;

       int t;

       for(p=L->next;p!=NULL;p=p->next){

              for(q=p->next;q!=NULL;q=q->next){

                     if(p->data>q->data){

                            t=p->data;

                            p->data=q->data;

                            q->data=t;

                     }

              }

       }

}

//打印列表

void printList(SortList  *L){

       SortList *p;

       p=L->next;

       while(p!=NULL){

                     printf("%d  ",p->data);

                     p=p->next;

       }

       printf("\n");

}

//主函数

int main(){

       SortList *L;

       L=(SortList*)malloc(sizeof(SortList));

       int array[8]={2,4,6,3,7,3,9,8};

       CreateSortList(L,array,8);

       printf("未排序前:");

       printList(L);

       sort(L);

       printf("已排序后:");

       printList(L);

      

}

 微笑本内容由安康学院"雨季"原创!

 

 

 

 

 

 

 

 

 

 

 

原创粉丝点击