直接上代码:
#includeusing namespace std; int const LIST_INIT_SIZE=100; typedef struct { int e; //线性表的值 }Polynomial; class Sqlist { private: Polynomial* L; int length; public: Sqlist(); //初始化线性表 ~Sqlist(); //销毁线性表 void CreatList(); void ClearList(); //将线性表置为空 bool ListEmpty(); //判断线性表是否为空 int ListLength(); //返回元素的长度 void GetElem(int i,int &e); //用e返回第i个数据元素的值 void PriorElem(int cur_e, int& pre_e); //用pre返回L中元素cur_e的前驱 void NextElem(int cur_e, int& next_e); //用next_e返回元素cur_e的后继 void ListinSert(int i, int e); //在L中第i个位置之前插入新的数据元素e void ListDelete(int i, int& e); //在L中删除第i个位置的元素并用e返回 void print(); //打印L中的内容 }; Sqlist::Sqlist() { //初始化线性表 L = new Polynomial[LIST_INIT_SIZE]; length = 0; } Sqlist::~Sqlist() { //销毁线性表 delete[] L; length = 0; } void Sqlist::CreatList() { for (int i = 1; i <= 10; i++) { L[i].e = i; length++; } } void Sqlist::ClearList() { //将线性表置为空 length = 0; } bool Sqlist::ListEmpty() { //判断线性表是否为空 if (length == 0) { return true; } else { return false; } } int Sqlist::ListLength() { //返回元素的长度 return length; } void Sqlist::GetElem(int i, int& e) { //用e返回第i个数据元素的值 if (i < 1 || i > length) { cout << "ERROR PLACE" << endl; return; } e = L[i].e; } void Sqlist::PriorElem(int cur_e, int& pre_e) { //用pre返回L中元素cur_e的前驱 int flag = 0; for (int i = 0; i < length; i++) { if (L[i].e == cur_e) { flag--; break; } flag++; } pre_e = L[flag].e; } void Sqlist::NextElem(int cur_e, int& next_e) { //用next_e返回元素cur_e的后继 int flag = 0; for (int i = 0; i < length; i++) { if (L[i].e == cur_e) { flag++; break; } flag++; } next_e = L[flag].e; } void Sqlist::ListinSert(int i, int e) { //在L中第i个位置之前插入新的数据元素e if (i < 1 || i >(length + 1)) { cout << "ERROR PLACE" << endl; return; } else if (length == LIST_INIT_SIZE) { cout << "The list is full" << endl; return; } else{ for (int j = length + 1; j > i; j--) { L[j].e = L[j - 1].e; } L[i].e = e; length++; cout << "Insert Successful" << endl; } } void Sqlist::ListDelete(int i, int& e) { //在L中删除第i个位置的元素并用e返回 if (i < 1 || i > length) { cout << "ERROR PLACE" << endl; return; } else if (ListEmpty()) { cout << "NULL LIST" << endl; return; } else { e = L[i].e; for (int j = i; j <= length; j++) { L[j].e = L[j + 1].e; } cout << "DELETE SUCCESSFUL" << endl; length--; } } void Sqlist::print() { //打印线性表中的值 if (ListEmpty()) { cout << "NULL LIST" << endl; return; } else { for (int i = 1; i <= length; i++) { cout << L[i].e << " "; } cout << endl; } } void implement() { Sqlist s; s.CreatList(); //创建一个线性表 s.print(); //打印创建的线性表 int e1 = 0; s.GetElem(3, e1); //用e1返回位置3处的线性表 cout << e1 << endl; s.ListinSert(10, 11); //在位置10处插入11 s.print(); s.ListDelete(10, e1); //删除位置10处的值 s.print(); s.NextElem(5, e1); //用e1返回位置5的后继元素 cout << e1 << endl; s.PriorElem(5, e1); //用e1返回5的前驱元素 cout << e1 << endl; } int main() { implement(); }
代码运行结果如下图:
ps:哪里有问题的话欢迎指正,打算尝试把严蔚敏版的书上算法都用C++代码实现一下



