# 双向链表的C++实现

xiaoxiao2021-03-01  13

struct node { int date; node* prev; node* next; }; 老样子，建立双链表的类

class doublelink { public: int doublelink_insert(doublelink* ptr,int position,int member); int doublelink_erase(doublelink* ptr, int position); void doublelink_display(doublelink* ptr, int num); int doublelink_getlength(doublelink* ptr); doublelink() { root = new node; root->prev = NULL; root->next = NULL; length = 0; } protected: private: int length; node* root; }; 插入元素

int doublelink::doublelink_insert(doublelink *ptr, int position, int member) { node* nodeinsert = new node; nodeinsert->date = member; if (ptr->doublelink_getlength(ptr) == 0) { root->next = nodeinsert; nodeinsert->prev = nodeinsert; nodeinsert->next = nodeinsert; ptr->length++; return 0; } else { if (position == 0) { /* root->next->prev = nodeinsert; nodeinsert->prev = root->next->prev; nodeinsert->next = root->next; root->next->prev = nodeinsert;*/ nodeinsert->prev = root->next->prev; nodeinsert->next = root->next; root->next->prev->next = nodeinsert; root->next->prev = nodeinsert; root->next = nodeinsert; ptr->length++; return 0; } else { node* current = root->next; for (int i = 0; i < position; i++) { current = current->next; } nodeinsert->next = current; nodeinsert->prev = current->prev; current->prev->next = nodeinsert; //nodeinsert->next = nodeinsert; current->prev = nodeinsert; ptr->length++; return 0; } } } 删除一个元素，注意0位置上的

int doublelink::doublelink_erase(doublelink* ptr, int position) { if (ptr->doublelink_getlength(ptr) == 0) { cout<<"链表为空，oop！！"<<endl; return 0; } else { if (ptr->doublelink_getlength(ptr) == 1) { ptr->root->next = NULL; ptr->length--; } else { node* deletenode = root->next; for (int i = 0 ; i < position; i++) { deletenode = deletenode->next; } deletenode->prev->next = deletenode->next; deletenode->next->prev = deletenode->prev; delete deletenode; ptr->length--; } } } 完整实现代码和测试结果