在已经创建线性表的基础上,求线性表的长度ListLength、求线性表L中指定位置的某个数据元素GetElem、查找元素LocateElem的算法都可以实现了。就在原程序的基础上增加:
02. 增加求线性表的长度ListLength的函数并测试;
03. 增加求线性表L中指定位置的某个数据元素GetElem的函数并测试;
04. 增加查找元素LocateElem的函数并测试;
[cpp] view plain copy
01.#include <stdio.h>
02.#include <malloc.h>
03.
04.#define MaxSize 50 //Maxsize将用于后面定义存储空间的大小
05.typedef int ElemType; //ElemType在不同场合可以根据问题的需要确定,在此取简单的int
06.typedef struct
07.{
08. ElemType data[MaxSize]; //利用了前面MaxSize和ElemType的定义
09. int length;
10.} SqList;
11.
12.//自定义函数声明部分
13.void CreateList(SqList *&L, ElemType a[], int n);//用数组创建线性表
14.void DispList(SqList *L);//输出线性表DispList(L)
15.bool ListEmpty(SqList *L);//判定是否为空表ListEmpty(L)
16.int ListLength(SqList *L); //求线性表的长度ListLength(L)
17.bool GetElem(SqList *L,int i,ElemType &e); //求某个数据元素值GetElem(L,i,e)
18.int LocateElem(SqList *L, ElemType e); //按元素值查找LocateElem(L,e)
19.
20.//实现测试函数
21.int main()
22.{
23. SqList *sq;
24. ElemType x[6]= {5,8,7,2,4,9};
25. ElemType a;
26. int loc;
27. CreateList(sq, x, 6);
28. DispList(sq);
29.
30. printf("表长度:%d\n", ListLength(sq)); //测试求长度
31.
32. if(GetElem(sq, 3, a)) //测试在范围内的情形
33. printf("找到了第3个元素值为:%d\n", a);
34. else
35. printf("第3个元素超出范围!\n");
36.
37. if(GetElem(sq, 15, a)) //测试不在范围内的情形
38. printf("找到了第15个元素值为:%d\n", a);
39. else
40. printf("第15个元素超出范围!\n");
41.
42. if((loc=LocateElem(sq, 8))>0) //测试能找到的情形
43. printf("找到了,值为8的元素是第 %d 个\n", loc);
44. else
45. printf("值为8的元素木有找到!\n");
46.
47. if((loc=LocateElem(sq, 17))>0) //测试不能找到的情形
48. printf("找到了,值为17的元素是第 %d 个\n", loc);
49. else
50. printf("值为17的元素木有找到!\n");
51.
52. return 0;
53.}
54.
55.//下面实现要测试的各个自定义函数
56.//用数组创建线性表
57.void CreateList(SqList *&L, ElemType a[], int n)
58.{
59. int i;
60. L=(SqList *)malloc(sizeof(SqList));
61. for (i=0; i<n; i++)
62. L->data[i]=a[i];
63. L->length=n;
64.}
65.
66.//输出线性表DispList(L)
67.void DispList(SqList *L)
68.{
69. int i;
70. if (ListEmpty(L))
71. return;
72. for (i=0; i<L->length; i++)
73. printf("%d ",L->data[i]);
74. printf("\n");
75.}
76.
77.//判定是否为空表ListEmpty(L)
78.bool ListEmpty(SqList *L)
79.{
80. return(L->length==0);
81.}
82.
83.//求线性表的长度ListLength(L)
84.int ListLength(SqList *L)
85.{
86. return(L->length);
87.}
88.
89.//求某个数据元素值GetElem(L,i,e)
90.bool GetElem(SqList *L,int i,ElemType &e)
91.{
92. if (i<1 || i>L->length)
93. return false;
94. e=L->data[i-1];
95. return true;
96.}
97.
98.//按元素值查找LocateElem(L,e)
99.int LocateElem(SqList *L, ElemType e)
100.{
101. int i=0;
102. while (i<L->length && L->data[i]!=e) i++;
103. if (i>=L->length)
104. return 0;
105. else
106. return i+1;
107.}
顺序表的基本运算2
最新推荐文章于 2020-11-02 22:19:03 发布