学习笔记——《大话数据结构》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;
class Sequential { public: 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;} 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()){ cout << "can't insert because input position i is not correct" << endl; return ERROR; } for(int j = getLength()-1 ; j>=i; j--){ _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
|