静态顺序表的简单实现

来源:互联网 发布:快递数据统计员 编辑:程序博客网 时间:2024/05/22 02:22

静态顺序表的增删查改

#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;    }}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.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;}

结果如下这里写图片描述

0 0
原创粉丝点击