双向链表C++ 的实现
本文是通过C++ 的知识实现数据结构中的双向链表,这里不多说 了,代码注释很清楚,
实现代码:
//double linkList implement with C++ template #includeusing namespace std; template class DlinkList; template class DNode { friend class DlinkList ;//指定前需声明 public: DNode(){next=NULL;prior=NULL;} ~DNode(){} private: DNode *next; DNode *prior; Type data; }; template class DlinkList { public: DlinkList() { // head=new DNode [sizeof(DNode )]; head=new DNode ; } ~DlinkList() { if(head->next==NULL) delete head; else { DNode *p=head->next; DNode *s=NULL; while(p) { s=p->next ; delete p; p=s; } } } void DeleteElement(size_t position) { DNode *p=head->next; size_t index=1; for(;index next ; if(p==NULL) return ; p->prior ->next =p->next ; p->next ->prior =p->prior ; delete p; } void InsertElement(T data,size_t position); void CreateDlinkList(T a[],int n); void PrintDlinkList(); private: DNode *head; }; template void DlinkList :: InsertElement (T data,size_t position) { DNode *p=head->next; size_t index=1; for(;index next; if(p==NULL) return; //DNode *s=new DNode [sizeof(DNode )]; DNode *s=new DNode ; s->data=data; s->next=p; s->prior=p->prior; p->prior->next=s; p->prior=s; } template void DlinkList ::CreateDlinkList(T a[],int n) { DNode *p=head; DNode *s=NULL; int i=0; for(;i [sizeof(DNode)]; s=new DNode ; s->data=a[i]; p->next=s; s->prior=p; p=s; } s->next=NULL; } template void DlinkList ::PrintDlinkList () { DNode *p=head->next; while(p) { cout< data< next; } } int main() { int a[10]={1,2,3,4,5,6,7,8,9,10}; DlinkList Dlist; Dlist.CreateDlinkList(a,10); Dlist.DeleteElement (3); Dlist.InsertElement(3,3); Dlist.PrintDlinkList(); return 0; } //double linkList implement with C++ Class / //*************************************************************************************
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!



