chunk list是对链表list一种改变,经典的list通过一个结构体node实现封装固定数量的信息,即每个结点大小完全一样,所不同的是存储的值不同。chunk list要求存储可变数量的元素。这点可以通过stl一个经典的容器vector来实现。
#include<iostream> #include<vector> #include<cstddef> #include<iterator> #include<algorithm> template<typename T> class Chunklist { private: struct node { std::vector<T> vec; node* link; }; node* head; void clear() { node* p = head; while(!p->link) { node* temp = p; p = p->link; delete temp; } delete p; } public: Chunklist() { head = new node(); head->link = NULL; } node* GetHead()const; void Insert(T* buffer,size_t size); bool Delete(T data); void Display()const; ~Chunklist() { clear(); } }; template<typename T> typename Chunklist<T>::node* Chunklist<T>::GetHead()const { return head; } template<typename T> void Chunklist<T>::Insert(T* buffer, size_t size) { // node haha; // node hh(); node* q = new node(); for(int i = 0; i < size; ++i) { q->vec.push_back(*(buffer+i)); } node* p = head; while(p->link) { p = p->link; } p->link = q; q->link = NULL; } template<typename T> bool Chunklist<T>::Delete(T data) { node* p = head->link; node* q = head; typename std::vector<T>::iterator iter; while(p) { iter = find(p->vec.begin(), p->vec.end(),data); if(iter != p->vec.end()) { break; } q = p; p = p->link; } if(p && iter != p->vec.end())//find it { p->vec.erase(iter); if(p->vec.size() == 0) { q->link = p->link; delete p; } return 1; } else { return 0; } } template<typename T> void Chunklist<T>::Display()const { node* p = head->link; std::cout<<"---------------chunk list----------------"<<std::endl; while(p) { for(typename std::vector<T>::iterator it = p->vec.begin(); it != p->vec.end(); ++it) { std::cout<<*it<<"\t"; } std::cout<<std::endl; p = p->link; } std::cout<<"------------------end---------------------"<<std::endl; } int main() { Chunklist<int> cl; int a[]={1,2,3,4,5}; cl.Insert(a,5); cl.Display(); int b[]={6,7}; cl.Insert(b,2); cl.Display(); int c[]={8}; cl.Insert(c,1); cl.Display(); cl.Delete(6); cl.Display(); cl.Delete(7); cl.Display(); cl.Delete(8); cl.Display(); return 0; }