线性表的查找插入删除运算
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了线性表的查找插入删除运算相关的知识,希望对你有一定的参考价值。
#include "seqlist.h" int main() { int a=5,b=4; cout<<"LObj.IsEmpty(): "<<LObj.IsEmpty()<<endl; cout<<"LObj.Length(): "<<LObj.Length()<<endl; LObj.Insert(-1,0); LObj.Insert(0,1); LObj.Insert(1,2); LObj.Insert(2,3); LObj.Insert(3,4); LObj.Insert(4,5); LObj.Insert(5,6); LObj.Insert(6,7); LObj.Insert(7,8); LObj.Insert(8,9); LObj.Insert(9,10); LObj.Insert(10,11); LObj.Output(cout); cout<<"LObj.Find(1,a):"<<LObj.Find(1,a)<<endl; cout<<"LObj.Search(b):"<<LObj.Search(b)<<endl; cout<<"LObj.Delete(5):"<<LObj.Delete(5); LObj.Output(cout); cout<<"Here end OK."<<endl; } #include "linearlist.h" const int SIZE=20; template <class T> class SeqList:public LinearList<T> { public: SeqList(int mSize); ~SeqList() { delete [] elements; } bool IsEmpty() const; int Length() const; bool Find(int i,T& x) const; int Search(T x) const; bool Insert(int i,T x); bool Delete(int i); bool Update(int i,T x); void Output(ostream& out)const ; private: int maxLength,n; //顺序表的最大长度 T *elements; //动态一维数组的指针 }; SeqList<int> LObj(SIZE); //定义了一个有5个整型值的顺序表对象 template <class T> SeqList<T>::SeqList(int mSize) { maxLength=mSize; elements=new T[maxLength]; n=0; } template <class T> bool SeqList<T>::IsEmpty() const { return n==0; } template <class T> int SeqList<T>::Length() const { return n; } template <class T> bool SeqList<T>::Find(int i,T& x) const { if(i<0||i>n-1) { cout<<"Out of Bounds"<<endl; } x=elements[i]; return true; } template <class T> int SeqList<T>::Search(T x) const { for(int j=0;j<n;j++) if(elements[j]==x) return j; return -1; } template <class T> bool SeqList<T>::Insert(int i,T x) { if(i<-1||i>n-1){ cout<<"Out of pounds"<<endl; return false; } if(n==maxLength){ cout<<"OverFlow"<<endl; return false; } for(int j=n-1;j>i;j--) elements[j+1]=elements[j]; elements[i+1]=x; n++; return true; } template <class T> bool SeqList<T>::Delete(int i) { if(!n){ cout<<"UnderFlow"<<endl; return false; } if(i<0||i>n-1) { cout<<"Out of Bounds"<<endl; return false; } for(int j=i+1;j<n;j++) elements[j-1]=elements[j]; n--; return true; } template <class T> bool SeqList<T>::Update(int i,T x) { if(i<0||i>n-1) { cout<<"Out of Bounds"<<endl; return false; } elements[i]=x; return true; } template <class T> void SeqList<T>::Output(ostream& out) const { for(int i=0;i<n;i++) out<<elements[i]<<" "; cout<<endl; } #include <iostream> using namespace std; template <class T> class LinearList { public: virtual bool IsEmpty() const=0; virtual int Length() const=0; virtual bool Find(int i,T& x) const=0; virtual int Search(T x) const=0; virtual bool Insert(int i,T x)=0; virtual bool Delete(int i)=0; virtual bool Update(int i,T x)=0; virtual void Output(ostream& out)const=0; protected: int n; //线性表的长度 };
以上是关于线性表的查找插入删除运算的主要内容,如果未能解决你的问题,请参考以下文章