静态顺序表的简单实现

xiaoxiao2021-02-28  70

静态顺序表的增删查改

#include<iostream> using namespace std; const int MAXSIZE = 100; template<class T> class Sqlist { public: Sqlist() { length = 0; } ~Sqlist() { length = 0; } void Insert(int i, int x);//指定位置插入 void pushback(int x);//尾插 void print();//遍历输出 void deleteAll();//清空顺序表 void popback();//尾删 void erase(int i);//指定位置删除 void find(int i);//用下标查找元素 private: int a[MAXSIZE]; int length;//元素的有效长度 }; template<class T> void Sqlist<T>::Insert(int i, int x) { i--; if (i<0 || i>length) cout << "输入错误" << endl; else {int j; for (j = length; j > i; j--) a[j] = a[j - 1]; a[i] = x; length++; } } template<class T> void Sqlist<T>::pushback(int x) { a[length] = x; length++; } template<class T> void Sqlist<T>::print() { if (length == 0) cout << "空表"<< endl; else { int i; for (i = 0; i < length; i++) cout << a[i] << ' '; cout <<"长度为 "<<length<< endl; } } template<class T> void Sqlist<T>::deleteAll() { length = 0; } template<class T> void Sqlist<T>::popback() { if (length == 0) cout << "空表" << endl; else length--; } template<class T> void Sqlist<T>::erase(int i) { i--; if (i<0 || i>length) cout << "输入错误" << endl; else { int j; for (j =i; j < length; j++) a[j] = a[j + 1]; length--; } } template<class T> void Sqlist<T>::find(int i) { i--; if (i<0 || i>length) cout << "输入错误" << endl; else { cout << "要找的元素是 " <<a[i]<< endl; } } template<class T> void Sqlist<T>::change(int i, int x) { i--; if (i<0 || i>length) cout << "输入错误" << endl; else { a[i] = x; cout << "已修改 "<< endl; } } int main() { Sqlist<int> l; l.pushback(1); l.pushback(1); l.Insert(3,4); l.Insert(2, 2); l.print(); cout <<"l.find(3);" << endl; l.find(3); cout << "l.change(2,9);" << endl; l.change(2,9); l.print(); cout << "l.erase(1);" << endl; l.erase(1); l.print(); cout << "l.popback()" << endl; l.popback(); l.print(); cout << "l.deleteAll()" << endl; l.deleteAll(); l.print(); return 0; }

结果如下

转载请注明原文地址: https://www.6miu.com/read-44291.html

最新回复(0)