将线性表的抽象数据类型定义在顺序表存储结构下用C++的类实现,由于线性表的数据元素类型不确定,所以采用模板机制。
1 头文件seqlist.h
2 #pragma once
3 #include <iostream>
4 const int MaxSize = 100;
5 template<class T>// 定义模板类
6 class SeqList
7 {
8 public:
9
10 SeqList() { Length = 0; }; // 无参构造函数,建立一个空的顺序表
11 SeqList(T a[], int n); // 有参构造函数,建立一个长度为n的顺序表
12 ~SeqList() {}; // 空的析构函数
13 int leng() { return Length; } // 求线性表的长度
14 T get(int i); // 按位查找第i个元素
15 int locate(T x); // 按值查找值为x的元素序号
16 void insert(int i, T x); // 在第i个位置插入值为x的元素
17 T Delete(int i); // 删除第i个元素
18 void printlist(); // 打印线性表
19
20 private:
21 T data[MaxSize];
22 int Length;
23
24 };
25
26 #pragma region 成员函数定义
27
28 template<class T>
29 inline SeqList<T>::SeqList(T a[], int n)
30 {
31 if (n > MaxSize)throw"参数非法";
32 for (int i = 0; i < n; i++)
33 data[i] = a[i];
34 Length = n;
35 }
36
37 template<class T>
38 T SeqList<T>::get(int i)
39 {
40 if (i<1 || i>Length)throw"查找位置非法";
41 else return data[i - 1];
42 }
43
44 template<class T>
45 int SeqList<T>::locate(T x)
46 {
47 for (int i = 0; i < Length; i++)
48 {
49 if (data[i] == x)
50 return i + 1;
51 }
52 return 0;
53 }
54
55 template<class T>
56 void SeqList<T>::insert(int i, T x)
57 {
58 if (Length >= MaxSize)throw "上溢";
59 if (i<1 || i>Length + 1)throw "插入位置非法";
60
61 for (int j = Length; j >= i; j--)
62 data[j] = data[j - 1];
63 data[i-1] = x;
64 Length++;
65 }
66
67 template<class T>
68 T SeqList<T>::Delete(int i)
69 {
70 if (Length == 0)throw"下溢";
71 if (i<1 || i>Length)throw"位置非法";
72 T x = data[i - 1];
73 for (int j = i; j < Length; j++)
74 data[j - 1] = data[j];
75 Length--;
76 return x;
77 }
78
79 template<class T>
80 void SeqList<T>::printlist()
81 {
82 for (int i = 0; i < Length; i++)
83 cout << data[i] << endl;
84
85 }
86 主函数
87 #include "seqlist.h"
88 using namespace std;
89 int main()
90 {
91 int arry[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
92 // 三种创建类对象的方法
93 SeqList<int> seqlist;
94 SeqList<int> seqlist1(arry,10);
95 SeqList<int>* seqlist2 = new SeqList<int>(arry, 10);
96 cout << seqlist1.get(5) << endl;
97 cout << seqlist2->get(5) << endl;
98 cout << seqlist1.locate(10) <<endl;
99 cout << seqlist2->locate(10) << endl;
100 seqlist1.insert(3, 11);
101 seqlist2->insert(4, 12);
102 seqlist1.Delete(1);
103 seqlist2->Delete(1);
104 seqlist1.printlist();
105 seqlist2->printlist();
106
107 system("pause");
108 return 0;
109 }
原文链接: https://www.cnblogs.com/smile233/p/8058647.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/265933
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!