大胖的部落格

Just a note

  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  112 随笔 :: 0 文章 :: 3 评论 :: 0 Trackbacks
#include <iostream>

using namespace std;

template 
<class T>
class LinearList {
public:
    LinearList(
int iSize = 10);
    
virtual    ~LinearList();
    
bool    IsEmpty();
    
int        Length();
    
bool    Find(int i, T& t) const;            // 返回第i个元素至t中
    int        Search(const T& t) const;            // 返回t所在位置
    LinearList&    Delete(int i, T& t);            // 删除第i个元素并将它返回至t中
    LinearList& Insert(int i, const T& t);        // 在第i个元素之后插入t
    void    Output(ostream& out)const;
private:
    
int    m_Length;
    
int    m_MaxSize;
    T    
*m_pElement;
}
;


template
<class T>
LinearList
<T>::LinearList(int iSize)
:m_MaxSize(iSize)
{
    m_Length 
= 0;
    m_pElement 
= new T[m_MaxSize];
}


template
<class T>
LinearList
<T>::~LinearList()
{
    delete []m_pElement;
}


template
<class T>
inline 
bool LinearList<T>::IsEmpty()
{
    
return (0 == m_Length);
}


template
<class T>
inline 
int LinearList<T>::Length()
{
    
return m_Length;
}


template
<class T>
bool LinearList<T>::Find(int i, T& t) const
{
    
if((i<1|| (i>m_Length)) {
        
return false;
    }

    t 
= m_pElement[i-1];
    
return true;
}


template
<class T>
int LinearList<T>::Search(const T& t) const
{
    
for(int i=0; i<m_Length: ++i) {
        
if(m_pElement[i] == t) {
            
return i+1;
        }

    }

    
return 0;
}


template
<class T>
LinearList
<T>& LinearList<T>::Delete(int i, T& t)
{
    
if((i>0&& (i<m_Length+1)) {
        t
=m_pElement[i-1];
        
for(int j=i; j<m_Length; ++j) {
            m_pElement[i
-1= m_pElement[i];
        }

        m_Length
--;
    }

    
return *this;
}


template
<class T>
LinearList
<T>& LinearList<T>::Insert(int i, const T& t)
{
    
if((m_Length < m_MaxSize) && (i>=0&& (i<m_Length+1)){
        
for(int j = m_Length; j>i; --j) {
            m_pElement[j] 
= m_pElement[j-1];
        }

        m_pElement[i] 
= t;
        m_Length
++;
    }

    
return *this;
}


template
<class T>
void LinearList<T>::Output(ostream& outconst
{
    
for(int i=0; i<m_Length; ++i) {
        
out<<m_pElement[i]<<" ";
    }

}


//重载全局的<<
template<class T>
ostream
& operator<<(ostream& out, LinearList<T>& x)
{
    x.Output(
out);
    
return out;
}

void main()
{
    LinearList
<char>    lList(11);
    lList.Insert(
0,'a');
    lList.Insert(
1,'b');
    lList.Insert(
2,'c');
    cout
<<lList<<endl;
}

posted on 2009-06-29 10:46 大胖 阅读(224) 评论(0)  编辑 收藏 引用 所属分类: Algorithm

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理