《数据结构一:链表》中链表采用单链表,当大量数据存储或者频繁操作链表时,导致速度过慢。主要原因是单链表反问效率问题,本文档对链表采用双向链表操作,同时对访问时开始位置做“二分”读取,经过测试速度有了很好的提高。 // //队列节点 template<class T> class CRtNode { public: CRtNode<T> *front;//指向前面节点 CRtNode<T> *next;//指向后面节点 T data;//数据 }; // template<class T> class CRtList: public CRtNode<T> { private: CRtNode<T>* mvo_front;//链表头 CRtNode<T>* mvo_back;//链表尾巴 long mvi_num;//长度 public: CRtList():mvo_front(NULL), mvo_back(NULL), mvi_num(0){ } ~CRtList(){ RemoveAll(); } int Insert_front(const T data);//插入链表头 int Insert_back(const T data);//插入链表尾巴 void RemoveAll();//全部删除队列数据 int RemoveAt(const int index);//删除队列中指定数据 T GetAt(const int index);//得到指定标号的数据 int length() const{ return mvi_num; } }; template<class T> inline T CRtList<T>::GetAt(const int index) { int i = 0; CRtNode<T>* temp; if( index - mvi_num / 2 >= 0 )//删除的标号在队列后半部分 { temp = mvo_back; while((i++) < (mvi_num - index - 1))//删除地址 { temp = temp->front; } } else删除的标号在队列前半部分 { temp = mvo_front; while((i++) < index)//删除地址 { temp = temp->next; } } return temp->data; } template<class T> inline int CRtList<T>::RemoveAt(const int index) { int i = 0; CRtNode<T>* temp; CRtNode<T>* next, *front; if (index < 0 || index >= mvi_num) return -1; if (index == (mvi_num - 1) )//当删除编号为结尾标号 { temp = mvo_back; mvo_back = mvo_back->front; mvo_back->next = NULL; delete temp; return 0; } if (index == 0 )//当删除编号为链表头标号 { temp = mvo_front; mvo_front = mvo_front->next; mvo_front->front = NULL; delete temp; return 0; } if( index - mvi_num / 2 >= 0 )//删除的标号在队列后半部分 { temp = mvo_back; while((i++) < (mvi_num - index - 1))//删除地址 { temp = temp->front; } } else删除的标号在队列前半部分 { temp = mvo_front; while((i++) < index)//删除地址 { temp = temp->next; } } front = temp->front; next = temp->next; delete temp; front->next = next; next->front = front; mvi_num--;//数据减少 return 0; } template<class T> inline void CRtList<T>::RemoveAll() { CRtNode<T>* temp;//下一个节点 while(mvo_front) { temp = mvo_front->next; delete mvo_front; mvo_front = temp; } mvo_back = NULL; mvi_num = 0; } template<class T> inline int CRtList<T>::Insert_front(const T data) { //存储新节点 CRtNode<T>* newNode = NULL; CRtNode<T>* temp = NULL; if (NULL == ( newNode = new CRtNode<T> )) return -1; newNode->data = data; newNode->next = NULL; newNode->front = NULL; if (NULL == mvo_front)//队列为空 { mvo_front = mvo_back = newNode; } else//在头部插入新节点 { temp = mvo_front; newNode->next = temp; temp->front = newNode; mvo_front = newNode; } mvi_num++; return 0; } template<class T> inline int CRtList<T>::Insert_back(const T data) { //存储新节点 CRtNode<T>* newNode = NULL; CRtNode<T>* temp = NULL; if (NULL == ( newNode = new CRtNode<T> )) return -1; newNode->data = data; newNode->next = NULL; newNode->front = NULL; if (NULL == mvo_front)//队列为空 { mvo_front = mvo_back = newNode; } else//在尾部插入新节点 { temp = mvo_back; mvo_back->next = newNode; newNode->front = temp; mvo_back = newNode; } mvi_num++; return 0; }