第3周项目1(1)- 顺序表的基本运算


(1)目的是要测试“建立线性表”的算法CreateList,为查看建表的结果,需要实现“输出线性表”的算法DispList。在研习DispList中发现,要输出线性表,还要判断表是否为空,

(2)在已经创建线性表的基础上,求线性表的长度ListLength、求线性表L中指定位置的某个数据元素GetElem、查找元素LocateElem的算法都可以实现了。就在原程序的基础上增加: 
  增加求线性表的长度ListLength的函数并测试; 
  增加求线性表L中指定位置的某个数据元素GetElem的函数并测试; 
  增加查找元素LocateElem的函数并测试;

代码:

[cpp] view plain copy
  1. #include <stdio.h>  
  2. #include <malloc.h>  
  3. #define MaxSize 50  
  4. typedef int ElemType;  
  5. typedef struct  
  6. {  
  7.     ElemType data[MaxSize];  
  8.     int length;  
  9. }SqList;  
  10. void CreateList(SqList *&L,ElemType a[],int n);  
  11. void DispList(SqList *L);  
  12. bool ListEmpty(SqList *L);  
  13. int ListLength(SqList *L);  
  14. bool GetElem(SqList *L,int i,ElemType &e);  
  15. int LocateElem(SqList *L, ElemType e);  
  16. int main()  
  17. {  
  18.     SqList *sq;  
  19.     ElemType x[6]= {5,8,7,2,4,9};  
  20.     ElemType a;  
  21.     int loc;  
  22.     CreateList(sq, x, 6);  
  23.     DispList(sq);  
  24.   
  25.     printf("表长度:%d\n", ListLength(sq));  //测试求长度  
  26.   
  27.     if(GetElem(sq, 3, a))  //测试在范围内的情形  
  28.         printf("找到了第3个元素值为:%d\n", a);  
  29.     else  
  30.         printf("第3个元素超出范围!\n");  
  31.   
  32.     if(GetElem(sq, 7, a))  //测试不在范围内的情形  
  33.         printf("找到了第7个元素值为:%d\n", a);  
  34.     else  
  35.         printf("第7个元素超出范围!\n");  
  36.   
  37.     if((loc=LocateElem(sq, 8))>0)  //测试能找到的情形  
  38.         printf("找到了,值为8的元素是第 %d 个\n", loc);  
  39.     else  
  40.         printf("值为8的元素没有找到!\n");  
  41.   
  42.     if((loc=LocateElem(sq, 17))>0)  //测试不能找到的情形  
  43.         printf("找到了,值为17的元素是第 %d 个\n", loc);  
  44.     else  
  45.         printf("值为17的元素没有找到!\n");  
  46.   
  47.     return 0;  
  48.   
  49. }  
  50. void CreateList(SqList *&L,ElemType a[],int n)  
  51. {  
  52.     int i;  
  53.     L=(SqList *)malloc(sizeof(SqList));  
  54.     for(i=0;i<n;i++)  
  55.     {  
  56.         L->data[i]=a[i];  
  57.     }  
  58.     L->length=n;  
  59. }  
  60. void DispList(SqList *L)  
  61. {  
  62.     int i;  
  63.     for(i=0;i<L->length;i++)  
  64.     {  
  65.         printf("%d",L->data[i]);  
  66.     }  
  67.     printf("\n");  
  68.   
  69. }  
  70. bool ListEmpty(SqList *L)  
  71. {  
  72.     return(L->length==0);  
  73. }  
  74. int ListLength(SqList *L)  
  75. {  
  76.     return(L->length);  
  77. }  
  78. bool GetElem(SqList *L,int i,ElemType &e)  
  79. {  
  80.     if (i<1 || i>L->length)  
  81.         return false;  
  82.     e=L->data[i-1];  
  83.     return true;  
  84. }  
  85. int LocateElem(SqList *L, ElemType e)  
  86. {  
  87.     int i=0;  
  88.     while (i<L->length && L->data[i]!=e) i++;  
  89.     if (i>=L->length)  
  90.         return 0;  
  91.     else  
  92.         return i+1;  
  93. }  


结果:

第3周项目1(1)- 顺序表的基本运算

学习心得:

  • 自己无从下手的时候一定要请教他人
  • “借力”的作用很大,“抄之有道”,最终结果还需自己去消化
  • 自行完成代码的运行实现有助于自己对代码的理解,多自己动手比