[C] 顺序表创建和就地逆序 →→→→→进入此内容的聊天室

来自 , 2021-02-21, 写在 C, 查看 101 次.
URL http://www.code666.cn/view/61d77652
  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. Status ListCreate_Sq(SqList &L)
  27. {
  28.     int n;
  29.     scanf("%d",&n);
  30.     L.elem=new ElemType[LIST_INIT_SIZE];//为顺序表分配一个大小为LIST_INIT_SIZE的数组空间
  31.     //L.elem=(ElemType *)malloc(LIST_INIT_SIZE*sizeof(ElemType));跟上一句作用一样,都是分配空间
  32.     if(!L.elem)
  33.         exit(OVERFLOW);//储存分配失败退出
  34.     L.length=0;//空表长度为0
  35.     L.listsize=LIST_INIT_SIZE;//顺序表大小为LIST_INIT_SIZE
  36.     for(int i=0;i<n;i++)//输入数组
  37.     {
  38.         scanf("%d",&L.elem[i]);
  39.         L.length++;
  40.     }
  41.     return OK;
  42. }
  43. void ListReverse_Sq(SqList &L)
  44. {
  45.     int a;
  46.     for(int i=0;i<L.length/2;i++)
  47.     {
  48.         a=L.elem[i];
  49.         L.elem[i]=L.elem[L.length-1-i];
  50.         L.elem[L.length-1-i]=a;
  51.     }
  52. }
  53.  
  54. int main() {
  55.     SqList L;
  56.     ElemType *p;
  57.  
  58.     if(ListCreate_Sq(L)!= OK) {
  59.         printf("ListCreate_Sq: 创建失败!!!\n");
  60.         return -1;
  61.     }
  62.  
  63.     ListReverse_Sq(L);
  64.  
  65.     if(L.length){
  66.                                 for(p=L.elem;p<L.elem+L.length-1;++p){
  67.                                     printf("%d ",*p);
  68.                                 }
  69.                                 printf("%d",*p);
  70.     }
  71.     return 0;
  72. }

回复 "顺序表创建和就地逆序"

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

captcha