[C] 有序顺序表的插入 →→→→→进入此内容的聊天室

来自 , 2019-11-17, 写在 C, 查看 104 次.
URL http://www.code666.cn/view/07a9d3fe
  1. //库函数头文件包含
  2. #include<stdio.h>
  3. #include<malloc.h>
  4. #include<stdlib.h>
  5.  
  6. //函数状态码定义
  7. #define TRUE        1
  8. #define FALSE       0
  9. #define OK          1
  10. #define ERROR       0
  11. #define INFEASIBLE -1
  12. #define OVERFLOW   -2
  13.  
  14. typedef int  Status;
  15.  
  16. //顺序表的存储结构定义
  17. #define LIST_INIT_SIZE  100
  18. #define LISTINCREMENT   10
  19. typedef int ElemType;  //假设线性表中的元素均为整型
  20. typedef struct{
  21.     ElemType* elem;   //存储空间基地址
  22.     int length;       //表中元素的个数
  23.     int listsize;     //表容量大小
  24. }SqList;    //顺序表类型定义
  25.  
  26. //函数声明
  27. Status ListInsert_SortedSq(SqList &L, ElemType e)
  28. {
  29.     int i;
  30.     ElemType *newelem;
  31.     if(L.length>=L.listsize)//扩容
  32.     {
  33.         newelem=(ElemType *)realloc(L.elem,(L.listsize+LISTINCREMENT)*sizeof(ElemType));
  34.         if(!newelem)exit(OVERFLOW);
  35.         L.elem=newelem;
  36.         L.listsize+=LISTINCREMENT;
  37.     }
  38.     for(i=L.length-1;i>=0&&*(L.elem+i)>e;i--)
  39.         L.elem[i+1]=L.elem[i];
  40.     L.elem[i+1]=e;
  41.     L.length++;
  42.     return OK;
  43. }
  44.  
  45. //顺序表初始化函数
  46. Status InitList_Sq(SqList &L)
  47. {
  48.     //开辟一段空间
  49.     L.elem = (ElemType*)malloc(LIST_INIT_SIZE * sizeof(ElemType));
  50.     //检测开辟是否成功
  51.     if(!L.elem){
  52.         exit(OVERFLOW);
  53.     }
  54.     //赋值
  55.     L.length = 0;
  56.     L.listsize = LIST_INIT_SIZE;
  57.  
  58.     return OK;
  59. }
  60.  
  61. //顺序表输出函数
  62. void ListPrint_Sq(SqList L)
  63. {
  64.     ElemType *p = L.elem;//遍历元素用的指针
  65.  
  66.  
  67.     for(int i = 0; i < L.length; ++i){
  68.         if(i == L.length - 1){
  69.             printf("%d", *(p+i));
  70.         }
  71.         else{
  72.             printf("%d ", *(p+i));
  73.         }
  74.     }
  75. }
  76. int main()
  77. {
  78.     //声明一个顺序表
  79.     SqList L;
  80.     //初始化顺序表
  81.     InitList_Sq(L);
  82.  
  83.     int number = 0;
  84.     ElemType e;
  85.  
  86.      scanf("%d", &number);//插入数据的个数
  87.  
  88.     for(int i = 0; i < number; ++i)
  89.     {
  90.                                 scanf("%d", &e);//输入数据
  91.         ListInsert_SortedSq(L, e);
  92.     }
  93.  
  94.     ListPrint_Sq(L);
  95.  
  96.     return  0;
  97. }
  98.  
  99.  

回复 "有序顺序表的插入"

这儿你可以回复上面这条便签

captcha