学习笔记——《大话数据结构》Ch3 数组与链表

第3章、线性表

定义抽象的线性表类型 Sequential:(sequential.h)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#ifndef SEQUENTIAL_H
#define SEQUENTIAL_H

#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0
#define MAXSIZE 1000

typedef int Status;
typedef int ElemType;

// 定义抽象的线性表类型Sequential及其接口
class Sequential
{
public:
// 在线性表s的第i个位置前插入元素e (i为计数脚标,从0开始)。设线性表元素数量为N,若i==N,则插在表尾
virtual Status insert(int i, ElemType e) = 0;
virtual const int getLength() = 0;
};

#endif

线性表的数组实现 Array:(array.h)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#ifndef ARRAY_H
#define ARRAY_H

#include <iostream>
#include "sequential.h"
using namespace std;

// 定义数组类型的线性表实现
class Array : public Sequential
{
public:
Array(){_length = 0;}

// 在线性表s的第i个位置前插入元素e (i为计数脚标,从0开始)。设线性表元素数量为N,若i==N,则插在表尾
Status insert(int i, ElemType e){
if(getLength() >= MAXSIZE){
cout << "can't insert because length reaches MAXSIZE" << endl;
return ERROR;
}
if(i < 0 || i > getLength()){ // 输入参数i的允许取值为 0~N
cout << "can't insert because input position i is not correct" << endl;
return ERROR;
}
for(int j = getLength()-1 ; j>=i; j--){ // 若插入位置不在表尾,则将后面的元素依次后移1位
_ptr[j+1] = _ptr[j];
}
_ptr[i] = e;
_length++;
return OK;
}
const int getLength(){ return _length;}
void print(){
cout << "print Array elements: (length = " << getLength() << ")" << endl;
for(int j = 0 ; j<=getLength()-1; j++){
cout << _ptr[j] << endl;
}
}

private:
ElemType _ptr[MAXSIZE];
int _length;

};


#endif

测试代码 main.cpp:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include "array.h"
using namespace std;

int main(){
Array a;
a.insert(0,11);
a.print();
a.insert(0,22);
a.print();
a.insert(1,33);
a.print();
a.insert(2,44);
a.print();
return 0;
}

输出:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
print Array elements: (length = 1)
11
print Array elements: (length = 2)
22
11
print Array elements: (length = 3)
22
33
11
print Array elements: (length = 4)
22
33
44
11