#include <utility>
#include <iterator>
using namespace std;
template<class T>
class DLinkedListIterator : public iterator<input_iterator_tag, T>{
public:
DLinkedListIterator(T* p){_ptr = p;}
T& operator * (){return *_ptr;}
DLinkedListIterator& operator = (const DLinkedListIterator &iter) {_ptr = iter._ptr;}
bool operator != (const DLinkedListIterator &iter) {return _ptr != iter._ptr;}
bool operator == (const DLinkedListIterator &iter) {return _ptr == iter._ptr;}
DLinkedListIterator& operator ++ (){
_ptr = (*_ptr).next;
return *this;
}
DLinkedListIterator operator ++ (int){
DLinkedListIterator tmp= *this;
_ptr = (*_ptr).next;
return tmp;
}
private:
T* _ptr;
};
template<class K, class V>
class DNode{
public:
pair<K, V> e;
DNode *pre, *next;
DNode(pair<K, V> e, DNode* pre, DNode* next){
this->e = e;
this->pre = pre;
this->next = next;
}
DNode(pair<K, V> e){
this->e = e;
pre = nullptr;
next = nullptr;
}
DNode(){
e = pair<K, V>(K(), V());
pre = nullptr;
next = nullptr;
}
};
template<class K, class V>
class DLinkedList{
public:
unsigned int count;
DNode<K, V> *vhead, *vtail;
typedef DLinkedListIterator<DNode<K, V>> iterator;
DLinkedList();
~DLinkedList();
iterator begin(){return iterator(vhead->next);}
iterator end(){return iterator(vtail);}
DNode<K, V>* insert(int pos, pair<K, V> e);
bool erase(int pos);
unsigned int size();
//warning!
bool insert(DNode<K, V> *pos, pair<K, V> e);
bool erase(DNode<K, V> *pos);
};
template<class K, class V>
DLinkedList<K, V>:: DLinkedList(){
count = 0;
vhead = new DNode<K, V>();
vtail = new DNode<K, V>();
vhead->next = vtail;
}
template<class K, class V>
DLinkedList<K, V>:: ~DLinkedList(){
while(vhead->next != vtail){
erase(0);
}
}
template<class K, class V>
DNode<K, V>* DLinkedList<K, V>:: insert(int pos, pair<K, V> e){
if(pos > count) return nullptr;
DNode<K, V> *cur = vhead;
for(int i = 0; i < pos; i++) cur = cur->next;
DNode<K, V> *newNode = new DNode<K, V>(e, cur, cur->next);
cur->next = newNode;
newNode->next->pre = newNode;
count++;
return newNode;
}
template<class K, class V>
bool DLinkedList<K, V>:: erase(int pos){
if(count == 0) return false;
DNode<K, V> *cur = vhead;
for(int i = 0; i < pos; i++) cur = cur->next;
DNode<K, V> *aim = cur->next;
cur->next = cur->next->next;
cur->next->pre = cur;
delete aim;
count--;
return true;
}
template<class K, class V>
unsigned int DLinkedList<K, V>:: size(){
return count;
}
template<class K, class V>
bool DLinkedList<K, V>:: insert(DNode<K, V> *pos, pair<K, V> e){
DNode<K, V> *newNode = new DNode<K, V>(e, pos, pos->next);
pos->next = newNode;
newNode->next->pre = newNode;
count++;
return true;
}
template<class K, class V>
bool DLinkedList<K, V>:: erase(DNode<K, V> *pos){
if(count == 0) return false;
DNode<K, V> *cur = pos->pre;
cur->next = cur->next->next;
cur->next->pre = cur;
delete pos;
count--;
return true;
}
06-18