线性表(C++)

来源:互联网 发布:sqlserver删除唯一约束 编辑:程序博客网 时间:2024/05/21 17:58

复习一下线性表的简单操作,以数组为存储结构

文件"sqlist.h"

#include <istream>using namespace std;const int LIST_INIT_SPACE=50; //存储空间初始分配量const int LIST_INC_SPACE=10; //分配增量template <class T>class Sq_list{private:T *elem; //存放空间基址int length; //当前长度int maxsize; //表的当前最大长度static bool flag; //是否已经排序的标志public:void Sq_listInit(T e[],int n) //用一个数组构造线性表{elem=new T[LIST_INIT_SPACE];if(!elem)exit(1);length=n;maxsize=LIST_INIT_SPACE;for(int i=0;i<n;i++)elem[i]=e[i];cout<<"线性表构造完成"<<endl;}int Locate_Elem(T e) //定位元素位置,重复的返回第一个的位置{int i=1;T *p=elem;while(i<=length && *p++!=e)i++;if(i<=length)return i;elsereturn -1; //表示定位失败}int Get_Length()  //返回当前表长{return length;}bool Sq_Insert(int pos,T e) //在表的第pos个元素后面插入{if(pos<1 || pos>length){cout<<"插入位置不合法"<<endl;return false;}if(length==maxsize) //此时表已满{int *newspace=new T[LIST_INIT_SPACE+LIST_INC_SPACE];if(!newspace)exit(1);for(int i=0;i<length;i++) //将原来的元素放回新表中newspace[i]=elem[i];delete[]elem;elem=newspace;maxsize+=LIST_INC_SPACE;}for(int i=length-1;i>pos-1;i--)elem[i+1]=elem[i];elem[pos]=e;length++;flag=false;return true;}bool Sq_Delete(int pos,T &e) //删除表中第pos个元素,值用e来装{if(pos<1 || pos>length){cout<<"参数不合法"<<endl;return false;}e=elem[pos-1];for(int i=pos;i<length;i++)elem[i-1]=elem[i];length--;return true;}void Sq_Sort()  //排序{for(int i=0;i<length;i++)for(int j=i+1;j<length;j++){if(elem[i]>elem[j]){T temp=elem[j];elem[j]=elem[i];elem[i]=temp;}}flag=true;}void Sq_unique() //去掉重复元素{if(!flag)Sq_Sort();int i=0;while(i<length){if(elem[i]!=elem[i+1])i++;else{if(i+1==length-1){elem[i]=elem[i+1];length--;return ;}else{for(int j=i+2;j<length;j++)elem[j-1]=elem[j];length--;}}}}void Sq_Print(){for(int i=0;i<length;i++)cout<<elem[i]<<"  ";cout<<endl;}};template <class T>bool Sq_list<T>::flag=false;

主函数"main.cpp"

#include "sqlist.h"#include <iostream>using namespace std;int main(){int a[8]={7,9,12,32,5,1,12,32};Sq_list<int> sq;sq.Sq_listInit(a,8);int l=sq.Get_Length();cout<<"length= "<<l<<endl;sq.Sq_Print();l=sq.Locate_Elem(32);cout<<"32 在表中为第"<<l<<"个元素"<<endl;sq.Sq_Sort();l=sq.Locate_Elem(32);cout<<"32 在排序后的表中为第"<<l<<"个元素"<<endl;sq.Sq_Print();sq.Sq_unique();cout<<"unique 后表的长度为:"<<sq.Get_Length()<<endl;sq.Sq_Print();if(sq.Sq_Insert(4,13))sq.Sq_Print();cout<<"现在表长为:"<<sq.Get_Length()<<endl;if(sq.Sq_Delete(7,l))sq.Sq_Print();cout<<"删除的元素为:"<<l<<endl;return 0;}

测试结果:

线性表构造完成length= 87  9  12  32  5  1  12  3232 在表中为第4个元素32 在排序后的表中为第7个元素1  5  7  9  12  12  32  32unique 后表的长度为:61  5  7  9  12  32在第四个元素后面插入131  5  7  9  13  12  32现在表长为:7删除第七个元素1  5  7  9  13  12删除的元素为:32Press any key to continue