C++字典的线性表实现。
#include <iostream> #include <assert.h> using namespace std; struct SchoolNo { int no; friend bool operator == (const SchoolNo &school1,const SchoolNo &school2) { return (school1.no==school2.no); } friend ostream & operator <<(ostream &_O,const SchoolNo &school) { _O<<school.no; return _O; } friend bool operator < (const SchoolNo &school1,const SchoolNo &school2) { return school1.no<school2.no; } friend bool operator > (const SchoolNo &school1,const SchoolNo &school2) { return school1.no>school2.no; } friend bool operator <= (const SchoolNo &school1,const SchoolNo &school2) { return school1.no<=school2.no; } friend bool operator >= (const SchoolNo &school1,const SchoolNo &school2) { return school1.no>=school2.no; } friend bool operator != (const SchoolNo &school1,const SchoolNo &school2) { return school1.no!=school2.no; } }; struct Information { friend ostream & operator<<(ostream &_O,const Information &_I) { _O<<"\t"<<_I.age<<"\t"<<_I.name<<endl; return _O; } int age; char name[13]; }; template<typename K,typename E> class SortedChain; template<typename K,typename E> class ChainNode { friend class SortedChain<K,E>; public: ChainNode():next(NULL){} ChainNode(K k,E e):key(k),data(e),next(NULL){} friend ostream &operator<<(ostream &_O,const ChainNode<K,E> &node) { _O<<node.key<<node.data; return _O; } private: E data; K key; ChainNode *next; }; template<typename K,typename E> class SortedChain { public: SortedChain() { first = new ChainNode<K,E>(); assert(first!=NULL); } ~SortedChain() { delete []first; first=NULL; } public: ChainNode<K,E> &Search(const K key)const//搜索。 { ChainNode<K,E> *p = first; while(p!=NULL) { if(p->key==key) break; p=p->next; } return *p; } void Insert(const K key,E &e) { ChainNode<K,E> *node = new ChainNode<K,E>(); node->data=e; node->key=key; node->next=NULL; ChainNode<K,E> *p = first; while(p->next!=NULL&& p->next->key<key)//重载 { p=p->next; } node->next = p->next; p->next=node; } friend ostream & operator<<(ostream &_O,const SortedChain<K,E> &node) { _O<<node.key; return _O; } void view() { ChainNode<K,E> *p = first; cout<<"学号"<<"\t"<<"年纪"<<"\t"<<"名字"<<endl; while(p->next!=NULL) { cout <<p->next->key<<p->next->data ; p=p->next; } } bool Remove(const K key,E &e) //删除。 { ChainNode<K,E> *p = first; while(p->next!=NULL && p->next->key!=key) { p = p->next; } ChainNode<K,E> *q = p->next; p->next = q->next; delete q; } ChainNode<K,E> *Begin()const //定位第一个。 { return (first->next); } ChainNode<K,E> &Next(ChainNode<K,E> *current)const//定位下一个。 { return *(current->next); } private: ChainNode<K,E> *first; }; int main() { SortedChain<SchoolNo,Information> a; Information _I1={100,"的吗西亚"}; Information _I2={10,"赵信"}; Information _I3={44,"光辉率狼"}; SchoolNo _No1={3}; SchoolNo _No2={1}; SchoolNo _No3={2}; a.Insert(_No1,_I1); a.Insert(_No2,_I2); a.Insert(_No3,_I3); a.view(); a.Remove(_No2,_I2); a.view(); return 0; }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。