顺序线性表-C++实现
1 #include <iostream>
2 using namespace std;
3
4 #define MAXSIZE 100
5 typedef int ElemType;
6
7 class SqList {
8 ElemType data[MAXSIZE];
9 unsigned int length;
10 public:
11 SqList(int length): length(length){};
12 void InitList()//初始化操作,输入若干个数据;:
13 {
14 ElemType e;
15 while (cin >> e)
16 data[length++] = e;
17 }
18 bool ListEmpty()//判断顺序线性表是否为空;
19 {
20 if (length)
21 return true;
22 else
23 return false;
24 }
25 void ClearList()//清空顺序线性表;
26 {
27 length = 0;
28 }
29 ElemType GetElem(int i, ElemType& e)//取得顺序线性表的第i个位置元素值并且返回;
30 {
31 if (i <= 0 && i >= length)
32 cerr << "error!, please check your input!" << endl;
33 return data[i-1];
34 }
35 int LocateElem(const ElemType& e)//判断顺序线性表中是否存在元素e,如果有返回该元素在顺序表中的位置,否则返回0
36 {
37 for (int i = 0; i < length; i++)
38 {
39 if (data[i] == e)
40 return i;
41 }
42 return 0;
43 }
44 void ListInsert(int i, const ElemType& e)//向顺序线性表的第i个位置插入元素e;
45 {
46 /*先判断要求是否合理*/
47 for (int j = length; j >= i; j--)
48 data[j] = data[j-1];
49 data[i-1] = e;
50 length++;
51 }
52 void ListDelete(int i, ElemType& e)//删除第i个位置的元素,并且用e返回其值;
53 {
54 /*先判断要求是否合理*/
55 e = data[i-1];
56 for (int j = i-1; j < length-1; j++)
57 data[j] = data[j+1];
58 length--;
59 }
60 unsigned int& ListLength()//返回线性表元素的个数
61 {
62 return length;
63 }
64 void show()//打印出线性表所有元素
65 {
66 for (int i =0; i < length; i++)
67 cout << data[i] << " ";
68 cout << endl;
69 }
70 void sort()//线性表排序,用的冒泡排序法,从小到大排序
71 {
72 for (int i = 0; i < length-1; i++)
73 for (int j = 0; j < (length-1 - i); j++)
74 if (data[j] > data[j+1])
75 swap(data[j], data[j+1]);
76 }
77
78 };
79
80
81 int main()
82 {
83 SqList L(0);
84 L.InitList();
85 cout << endl;
86 L.show();
87 L.ListInsert(1, 6);
88 L.show();
89 ElemType e;
90 L.ListDelete(1, e);
91 L.show();
92 cout << e << endl;
93 cout << boolalpha << L.ListEmpty() << endl;
94
95 cout <<"----sort-----" << endl;
96 L.sort();
97 L.show();
98
99 return 0;
100 }