Chinaunix首页 | 论坛 | 博客
  • 博客访问: 23813
  • 博文数量: 8
  • 博客积分: 1410
  • 博客等级: 上尉
  • 技术积分: 105
  • 用 户 组: 普通用户
  • 注册时间: 2006-12-07 16:18
文章分类

全部博文(8)

文章存档

2008年(8)

我的朋友
最近访客

分类: C/C++

2008-07-22 10:40:37

#ifndef __LINEAR_LIST_H__
#define __LINEAR_LIST_H__

#include <iostream>
using namespace std;

template <class T>
class LinearList
{
public:
    LinearList(int MaxListSize = 10);
    ~LinearList()
    {
        delete []element;
    }
    bool IsEmpty() const
    {
        return length==0;
    }
    bool Find(int k, T& x) const;
    int Search(const T& x) const;

    LinearList<T>& Delete(int k, T& x);
    LinearList<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 (Find(k,x))
    {
        for(int i=k; i<length; i++)
            element[i-1] = element[i];
        length--;
        return *this;
    }
    else
        throw;
}

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

#endif

阅读(670) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~