c++實現(線性表)

來源:互聯網
上載者:User

/*
線性表的幾個基本操作(ADT)
1:線性表的初始化:  create()
2:線性表的撤銷:   destroy()
3:判斷是否為空白:   isempty()
4:求線性表的長度: length()
5:取表中元素:     find(k,x)
6:按值尋找:       search(x)
7:插入操作:       insert(k,x)
8:刪除操作:       delete(k,x)
9:線性表的輸出:  output(k,x)
*/

//線性表
#ifndef AbstractList
#define AbstractList
template<class T>
class AbstractList
{
public:
     virtual bool IsEmpty() const=0;
     virtual int  Length()  const=0;
     virtual bool Find(int K,T&x) const=0;
     virtual int Search(const T& x) const=0;
     virtual AbstractList<T>& Delete(int k,T& x)=0;
     virtual AbstractList<T>& Insert(int k,const T& x)=0;
     virtual void Output(ostream& out) const=0;
};

 

template<class T>
class LinearList::AbstractList<T>
{
public:
     LinearList(int MaxListSize=10);
     ~LinearList(){ delete [] element;}
     bool IsEmpty() const{ return length==0;}
     int Length()const{return length;}
     bool Find(int k,T & x)const;
     int Search(const T& x)const;
     LinearList<T>& Delete(int k ,T& x);
     LinearLists<T>& Insert(int k,const T& x);
     void Output(ostream& out) const;
private:
     int length;
     int MaxSize;
     T *element;
};

 

template<class T>
LinearList<T>::LinearList(int MaxListSize)
{
     MaxSize=MaxListSize;
     element=new T[MaxSize];
     length=0;
}

 

template<class T>
bool LinearList<T>::Find(int k,T & x)const
{
     if(k<1 || k>length) return false;
     x=element[k-1];
     return true;
}

 

template<class T>
int LinearList<T>::Search(const T& x)const
{
     for(int i=0;i<length;i++)
    {
          if(element[i]==x)
         {
               return ++i;
          }
     }
      return 0;
}

 

template<class T>
LinearList<T>& LinearList<T>::Delete(int k,T& x)
{
     if( k < 0 || K > length) throw OutOfBounds();
     for( int i = k ; i < length ; i++ )
    {
          element[i-1]=element[i];
     }
      length--;
      return *this;
}

 

template<class T>
LinearList<T>& LinearList<T>::Inseart(int k,const T& x)
{
      if ( k < 0 || k > length+1) throw OutofBounds();
      if(length == MaxSize) throw NoMem();
      for(int i = length -1 ;i >= k;i--)
      {
            element[i+1]=element[i];
      }
       element[k]=x;
       length++;
        return *this;
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.