1. 程式人生 > >列表的c++實現(類模板,包含順序實現和單鏈表、雙鏈表)

列表的c++實現(類模板,包含順序實現和單鏈表、雙鏈表)

#ifndef LIST_H_INCLUDED
#define LIST_H_INCLUDED
#include <iostream>

using namespace std;
template <class elemType>
class List{
  public:
      virtual int length() const=0;
      virtual int Search(const elemType &x) const=0;
      virtual elemType visit(int i) const=0;
      virtual void Insert(int i,const elemType &x)=0;
      virtual void Remove(int i)=0;
      virtual void Clear()=0;
      virtual void traverse() const=0;
      virtual ~List(){};
};

class OutOfBound{};
class IllegalSize{};
template <class elemType>
class seqList:public List<elemType>{
  private:
      elemType *data;
      int currentLength;
      int maxSize;
      void doubleSpace();
  public:
    seqList(int initSize=10);
    ~seqList(){delete [] data;}
    int length() const;
    int Search(const elemType &x) const;
    elemType visit(int i) const;
    void Insert(int i,const elemType &x);
    void Remove(int i);
    void Clear();
    void traverse() const;
};

template <class elemType>
class linkList:public List<elemType>
{
private:
    struct node{
      elemType data;
      node *next;
      node(const elemType &x,node *p=NULL){
        data=x; next=p;
      }
      node():next(NULL){}
      ~node(){}
    };
    node *head;
public:
    linkList();
    ~linkList(){Clear(); delete head;}
    int length() const;
    int Search(const elemType &x) const;
    elemType visit(int i) const;
    void Insert(int i,const elemType &x);
    void Remove(int i);
    void Clear();
    void traverse() const;
};

template <class elemType>
class dlinkList:public List<elemType>{
  private:
      struct node{
        elemType data;
        node *prev,*next;
        node(const elemType &x,node *p=NULL,node *n=NULL){data=x;next=n;prev=p;}
        node():next(NULL),prev(NULL){}
        ~node(){}
      };
      node *head,*tail;
      int currentLength;

  public:
      dlinkList();
      ~dlinkList(){Clear();delete head; delete tail;}

      void Clear();
      int length() const {return currentLength;}
      void Insert(int i,const elemType &x);
      void Remove(int i);
      int Search(const elemType &x) const;
      elemType visit(int i) const;
      void traverse() const;
};


#include "seqList.cpp"
#include "linkList.cpp"
#include "dlinkList.cpp"
#endif // LIST_H_INCLUDED