代码从课件上扒的,修改部分代码,可运行,学习备考用
#include
using namespace std;
template
class SeqList {
T* data;
int MaxSize;
int last;
public:
SeqList(int MaxSize = defaultSize);
~SeqList() { delete[] data; }
T& operator[](int i);
int Length() const { return last + 1; }
int Find(T& x) const;
int IsIn(T& x);
int Insert(T& x, int i);
int Remove(T& x);
int Next(T& x);
int Prior(T& x);
int IsEmpty() { return last == -1; }
int IsFull() { return last == MaxSize - 1; }
T Get(int i) {
return i < 0 || i > last ? nullptr : data[i];
}
void Union(SeqList& LA, SeqList LB);
void Intersection(SeqList& LA, SeqList& LB);
void DisplayData();
};
template
SeqList ::SeqList(int sz) {
if (sz > 0) {
MaxSize = sz;
last = -1;
data = new T[MaxSize];
if (data == nullptr) {
MaxSize = 0;
last = -1;
return;
}
}
}
template
T& SeqList::operator[](int i) {
if (i < 0 || i > MaxSize - 1) {
cerr << "序列下标越界" << endl;
static T default_value = T();
return default_value;
}
return data[i];
}
template
int SeqList::Find(T& x) const {
int i = 0;
while (i <= last && data[i] != x) {
i++;
}
if (i > last) return -1;
else return i;
}
template
int SeqList::IsIn(T& x) {
int i = 0, found = 0;
while (i <= last && !found) {
if (data[i] != x) i++;
else found = 1;
}
return found;
}
template
int SeqList::Insert(T& x, int i) {
if (i < 0 || i > last + 1 || last == MaxSize - 1) {
return 0;
}
else {
last++;
for (int j = last; j > i; j--) {
data[j] = data[j - 1];
}
data[i] = x;
return 1;
}
}
template
int SeqList::Remove(T& x) {
int i = Find(x);
if (i >= 0) {
last--;
for (int j = i; j <= last; j++) {
data[j] = data[j + 1];
}
return 1;
}
return 0;
}
template
int SeqList::Next(T& x) {
int i = Find(x);
if (i >= 0 && i < last) return i + 1;
else return -1;
}
template
int SeqList::Prior(T& x) {
int i = Find(x);
if (i >= 0 && i <= last) return i - 1;
else return -1;
}
template
void SeqList::Union(SeqList& LA,SeqList LB) {
int n = LA.Length();
int m = LB.Length();
for (int i = 1; i <= m; i++) {
T x = LB.Get(i);
int k = LA.Find(x);
if (k == -1)
{
LA.Insert(n + 1, x); n++;
}
}
}
template
void SeqList::Intersection(SeqList& LA,SeqList& LB) {
int n = LA.Length();
int m = LB.Length();
int i = 0;
while (i < n) {
T x = LA.Get(i);
int k = LB.Find(x);
if (k == -1) { LA.Remove(x); n--; }
else i++;
}
}
template
void SeqList::DisplayData() {
for (int i = 0; i < last; i++) {
cout << data[i] << " ";
}
cout << endl;
}
#include "SeqList.cpp"
int main() {
//cout << "test" << endl;
SeqList arr(6);
SeqList brr(4);
for (int i = 0; i < 6; i++) {
arr.Insert(i, i);
}
for (int i = 0,k = 1; i < 4; i++) {
k += 2*i;
brr.Insert(k, i);
}
arr.DisplayData();
brr.DisplayData();
int valueToRemove = 2;
int f = arr.Remove(valueToRemove);
arr.DisplayData();
return 0;
}