C++双向链表的建立(无头节点)
2017-10-22 19:57
288 查看
#ifndef doublychain_ #define doublychain_ #include<iostream> #include<algorithm> #include"chainNode.h" using namespace std; template<typename T> class doublychain { public: doublychain(); ~doublychain(); void insert(const int theIndex, const T& theElement); void erase(int theIndex); void output(ostream& out); protected: chainNode<T>*firstNode; chainNode<T>*lastNode; int listSize; }; template<typename T> doublychain<T>::doublychain() { firstNode = lastNode = NULL; listSize = 0; } template<typename T> doublychain<T>::~doublychain() { while (firstNode != NULL) { chainNode<T>*next = firstNode->next; delete firstNode; firstNode = next; } delete firstNode; } template<typename T> void doublychain<T>::insert(const int theIndex, const T& theElement) { if (theIndex == 0) { firstNode = new chainNode<T>(theElement, firstNode); lastNode = firstNode; firstNode->pre = NULL; lastNode->next = NULL; } else { chainNode<T>*p = firstNode; chainNode<T>*q; for (int i = 0; i < theIndex -1; ++i) p = p->next; p->next = new chainNode<T>(theElement, p->next); q = p->next; q->pre = p; if (theIndex ==listSize) lastNode = p->next; } ++listSize; } template<typename T> void doublychain<T>::erase(int theIndex) { chainNode<T>*deleteNode; chainNode<T>*q; if (theIndex = 0) { deleteNode=firstNode; q = firstNode->next; firstNode = firstNode->next; q->pre = NULL; } else { chainNode<T>*p = firstNode; for (int i = 0; i < theIndex - 1; i++) p = p->next; deleteNode=p->next; q = p->next->next; p->next = p->next->next; q->pre = p; if (deleteNode == lastNode) lastNode = p; } delete deleteNode; --listSize; } //对双向链表进行测试 template<typename T> void doublychain<T>::output(ostream& out) { /*for (chainNode<T>*p = firstNode; p != NULL; p=p->next) cout << p->element << " ";*/ for (chainNode<T>*p = lastNode; p !=NULL; p = p->pre) cout << p->element << " "; } #endif
相关文章推荐
- C++双向链表的建立(无头节点)
- C++双向链表的建立(无头节点)
- C++双向链表的建立(无头节点)
- C++双向链表的建立(无头节点)
- C++双向链表的建立(无头节点)
- C++双向链表的建立(无头节点)
- C++双向链表的建立(无头节点)
- C++双向链表的建立(无头节点)
- C++双向链表的建立(无头节点)
- C++双向链表的建立(无头节点)
- C++双向链表的建立(无头节点)
- C++双向链表的建立(无头节点)
- C++双向链表的建立(无头节点)
- C++双向链表的建立(无头节点)
- C++双向链表的建立(无头节点)
- C++构建循环链表(无头节点)
- C++单链表的建立(有头节点)
- 数据结构_队列_用链表动态建立释放节点实现队列各种操作_C++实现
- C++构建循环链表(无头节点)
- C++单链表的建立(有头节点)